How To Exclude A Value In A ModelMultipleChoiceField?

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

提交回复
热议问题