Django ModelForm overriding __init__
Asked Answered
O

2

6

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!

Orectic answered 14/12, 2015 at 14:58 Comment(0)
O
7

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
Orectic answered 16/12, 2015 at 22:32 Comment(0)
H
0

That last line is overwriting the queryset assigned in previous one. Remove it.

Havre answered 14/12, 2015 at 15:5 Comment(2)
AFAIK it is overwriting the choice set for the form widget, and this overwrite would be redundant I agree, but no eraser of the queryset at all.Orectic
I am not sure but, @daniel-roseman is an answer or it could be a comment on answer?Slover

© 2022 - 2024 — McMap. All rights reserved.