Django ModelForm覆盖__init__ [英] Django ModelForm overriding __init__

查看:105
本文介绍了Django ModelForm覆盖__init__的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用当前用户所属的Django组填充ModelForm的Select列表。

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.

这是我的代码:

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

请注意,如果我在第一个启用调试器 __ init __ 方法的行,并沿函数前进,该行:

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!

推荐答案

这就是我最终解决此问题的方式:

This is how I ended up solving this:

我错误地选择了字段类型:正确的是ModelChoiceField:

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

这篇关于Django ModelForm覆盖__init__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆