简体   繁体   English

Django ModelForm覆盖__init__

[英]Django ModelForm overriding __init__

I'm trying to populate a Select list of a ModelForm, with the Django groups the current users belongs to. 我正在尝试使用当前用户所属的Django组填充ModelForm的Select列表。

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: 请注意,如果我在__init__方法的第一行启用调试器,并在整个函数中向前一步,则行:

    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! 谢谢!

This is how I ended up solving this: 这就是我最终解决这个问题的方法:

I was wrongly choosing the type of the field: The correct one is ModelChoiceField: 我错误地选择了字段的类型:正确的是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

That last line is overwriting the queryset assigned in previous one. 最后一行是覆盖前一行中分配的查询集。 Remove it. 去掉它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM