1

I am working on a hard django project and I am stuck again. In my implementation of ModelForm, I have this form. So I wanna filter the queryset in the assign field so if I do this assign.objects.filter(user_id=1) it is gonna show every user this queryset but I wanna put the request user in this queryset. How can I access the current request user?

class SomeModelForm(forms.ModelForm):

    assign = forms.ModelMultipleChoiceField(
        widget=forms.CheckboxSelectMultiple,
        queryset=Assign.objects.all(),
    )

    class Meta:
        model = SomeModel
        fields = '__all__'
  • 3
    Hey man, does this answer your question? [How to use the request in a ModelForm in Django](https://stackoverflow.com/questions/8841502/how-to-use-the-request-in-a-modelform-in-django) – Dante Jul 18 '20 at 09:07

2 Answers2

2

Pass one additional user object to your form, and then filter based on the user.

forms.py

class SomeModelForm(forms.ModelForm):
    assign = forms.ModelMultipleChoiceField(
        widget=forms.CheckboxSelectMultiple,
        queryset=Assign.objects.none(),
    )

    class Meta:
        model = SomeModel
        fields = '__all__'

   def __init__(self, *args, **kwargs):
       user = kwargs.pop('user', None)
       super().__init__(*args, **kwargs)
       if user:
           self.fields['assign'].queryset = Assign.objects.filter(user=user)

views.py

form = SomeModelForm(user=request.user)
minglyu
  • 2,958
  • 2
  • 13
  • 32
0

you can do it by just writing

username = request.user.username
print(username)

It will print the current logged in username.

Ajay Lingayat
  • 1,465
  • 1
  • 9
  • 25