How To Exclude A Value In A ModelMultipleChoiceField?

前端 未结 2 908
清歌不尽
清歌不尽 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: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
    

提交回复
热议问题