How To Exclude A Value In A ModelMultipleChoiceField?

前端 未结 2 904
清歌不尽
清歌不尽 2021-01-20 03:53

I do not want the logged in user to show up on this ModelMultipleChoiceField in order to restrict themselves from creating a following relationship with themselves? So how d

相关标签:
2条回答
  • 2021-01-20 04:09

    Define an __init__ method for the form class. Pass the logged in userid to the form while initializing it, this will work with a model form.

    def __init__(self, *args, **kwargs):
        user_id = kwargs.pop('user_id')
        super(Add_Profile, self).__init__(*args, **kwargs)
        self.fields['follows'] = forms.ModelMultipleChoiceField(queryset=UserProfile.objects.filter(~Q(user_id=user_id)))
    

    While initializing your form, you can pass user_id

    address_form = Add_Profile(request.POST, user_id=request.user.id)
    
    0 讨论(0)
  • 2021-01-20 04:11

    You can definitely do it using forms.Form instead of forms.ModelForm with something along the lines of this example in the docs:

    from django import forms
    from django.contrib.auth import get_user_model
    
    class Add_Profile(forms.Form):
        follows = forms.ModelMultipleChoiceField(queryset=None)
    
        def __init__(self, user=None, *args, **kwargs):
            super(Add_Profile, self).__init__(*args, **kwargs)
            if user is not None:
                self.fields['follows'].queryset = get_user_model().objects.exclude(pk=user.pk)
            else:
                self.fields['follows'].queryset = get_user_model.objects.all()
    

    Just pass in the user you wish to exclude when you instantiate the form:

    form = Add_Profile()  # all users will be present in the dropdown
    some_guy = User.objects.get(pk=4)
    form = Add_Profile(user=some_guy)  # all users except some_guy will be present
    
    0 讨论(0)
提交回复
热议问题