Django ModelForm overriding __init__

后端 未结 2 1981
小蘑菇
小蘑菇 2021-01-05 18:15

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.

相关标签:
2条回答
  • 2021-01-05 18:29

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

    0 讨论(0)
  • 2021-01-05 18:46

    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
    
    0 讨论(0)
提交回复
热议问题