Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get request.user in queryset in a ModelForm with a ModelChoiceField that contains a RadioSelect widget

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 ?

like image 938
pebox11 Avatar asked Jul 20 '15 13:07

pebox11


1 Answers

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)
like image 150
Alasdair Avatar answered Oct 19 '22 13:10

Alasdair