Django ModelForm 覆盖 __init__ [英] Django ModelForm overriding __init__
问题描述
我正在尝试使用当前用户所属的 Django 组填充 ModelForm 的选择列表.
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.
我会错过什么?谢谢!
推荐答案
这就是我最终解决这个问题的方法:
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屋!