Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ModelForm overriding __init__

I'm trying to populate a Select list of a ModelForm, with the Django groups the current users belongs to.

No errors arise, but I get only an empty Select list.

This is my code:

class ArchiveForm(forms.ModelForm):

    class Meta:
        model = Archive
        fields = ['tags', 'version', 'sharegp']
        localized_fields = None
        labels = {'tags': 'Related Keywords'}


    sharegp = forms.ChoiceField(label='Share with groups')

    def __init__(self, user, *args, **kwargs):

        #import pudb;pudb.set_trace()
        self.user = user
        super(ArchiveForm, self).__init__(*args, **kwargs)
        self.fields['sharegp'].queryset = Group.objects.filter(user=self.user)
        self.fields['sharegp'].widget.choices = self.fields['sharegp'].choices

Note that if I enable the debugger in the first line of the __init__ method, and step forward all along the function, the line:

    self.fields['sharegp'].queryset

Gives the correct list containing the groups for that user, but that is not passed to the actual form.

What could I be missing? Thank you!

like image 952
Martin0x777 Avatar asked Dec 14 '15 14:12

Martin0x777


1 Answers

This is how I ended up solving this:

I was wrongly choosing the type of the field: The correct one is ModelChoiceField:

class ArchiveForm(forms.ModelForm):

    class Meta:
        model = Archive
        fields = ['tags', 'version', 'sharegp']
        localized_fields = None
        labels = {'tags': 'Related Keywords'}

    user = None
    usergroups = None
    sharegp = forms.ModelChoiceField(label='Share with groups', queryset=usergroups)

    def __init__(self, user, *args, **kwargs):

        self.user = user
        self.usergroups = Group.objects.filter(user=self.user)
        super(ArchiveForm, self).__init__(*args, **kwargs)
        self.fields['sharegp'].queryset = self.usergroups
like image 120
Martin0x777 Avatar answered Nov 01 '22 10:11

Martin0x777