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
?
__init__
is exactly the right solution, and the fact that you have a custom class is irrelevant. Please show what you have tried and the errors you got. – TelemotorgoModelChoiceField
inside your ModelForm is probably a bad idea (it makes the code confusing and stops you reusing it in other classes). Havinguser_choice
defined insidegoModelChoiceField
is certainly wrong. – Hausmannuser_choice
outsidegoModelChoiceForm
and insideMeta
class. It is strange though how it works in both ways. Thank you. – Mylesmylittauser_choice
field shouldn't be defined in the Meta class either. – HausmannMeta
class then I would have to also move out thegoModelChoiceField
subclass and make it a class by itself. But this wouldn't make my code more sparse? I am asking... I am not experienced as you or @Daniel Roseman of course. Thank you again for your patience and time you spend. I appreciate that. – Mylesmylittarequest.user
, which still needs to be done in__init__
. – Telemotor__init__
. Thank you – Mylesmylitta