Django ModelForm overriding __init__

Martin0x777 picture Martin0x777 · Dec 14, 2015 · Viewed 9.4k times · Source

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!

Answer

Martin0x777 picture Martin0x777 · Dec 16, 2015

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