I would like to ask the community the following regarding passing request.user
to a queryset
in ModelForm
. My ModelForm
is:
class goForm(ModelForm):
user_choice = goModelChoiceField(
widget=forms.RadioSelect,
queryset=Document.objects.all().filter(who_upload=request.user),
empty_label=None,
to_field_name='docfile',
label = 'Please select'
)
class Meta:
model = go
fields = ['user_choice']
With
class goModelChoiceField(forms.ModelChoiceField):
def label_from_instance(self, obj):
return "'%s' uploaded on %s" % (obj.file_name,
obj.when_upload.date())
All the answers I have found refer to either passing request.user
to __init__
or populate the goForm
in the view with the filtered selection. However nothing seems to work in my case since I have sub-classed the form to return a specific string and also I am using
the RadioSelect
widget that specifically needs the queryset
as an argument (I am not 100% sure about that). So how can I pass request.user
in user_choice
?
The model choice field docs show how you can set the queryset in the __init__
method.
class goForm(ModelForm):
user_choice = goModelChoiceField(
widget=forms.RadioSelect,
queryset=None,
empty_label=None,
to_field_name='docfile',
label = 'Please select'
)
def __init__(self, user, *args, **kwargs):
super(goForm, self).__init__(*args, **kwargs)
self.fields['user_choice'].queryset = Document.objects.all().filter(who_upload=user)
class Meta:
model = go
fields = ['user_choice']
Note that the __init__
method takes the user as an argument now, so remember to pass it wherever you instantiate your form in your view. For example:
form = goForm(user=request.user, data=request.POST)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With