1
我正在使用Django表单视图,并且我想为每个用户输入自定义选项以供我的Choicefield
使用。CBV Django表单查看ChoiceField的设置数据
我该怎么做?
我可以使用也许get_initial
函数? 我可以覆盖该字段吗?
我正在使用Django表单视图,并且我想为每个用户输入自定义选项以供我的Choicefield
使用。CBV Django表单查看ChoiceField的设置数据
我该怎么做?
我可以使用也许get_initial
函数? 我可以覆盖该字段吗?
当我想改变某些形式的东西,如标签文本,添加必需的字段或过滤选择列表等。我遵循一个模式,我使用ModelForm并添加一些实用方法,它包含我的首要代码(这有助于保持__init__
整洁)。然后从__init__
调用这些方法来覆盖默认值。
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('country', 'contact_phone',)
def __init__(self, *args, **kwargs):
super(ProfileForm, self).__init__(*args, **kwargs)
self.set_querysets()
self.set_labels()
self.set_required_values()
self.set_initial_values()
def set_querysets(self):
"""Filter ChoiceFields here."""
# only show active countries in the ‘country’ choices list
self.fields["country"].queryset = Country.objects.filter(active=True)
def set_labels(self):
"""Override field labels here."""
pass
def set_required_values(self):
"""Make specific fields mandatory here."""
pass
def set_initial_values(self):
"""Set initial field values here."""
pass
如果ChoiceField
是你要被定制的唯一的事情,这是所有你需要:
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('country', 'contact_phone',)
def __init__(self, *args, **kwargs):
super(ProfileForm, self).__init__(*args, **kwargs)
# only show active countries in the ‘country’ choices list
self.fields["country"].queryset = Country.objects.filter(active=True)
然后,您可以让您的FormView控件使用这种形式,像这样:
class ProfileFormView(FormView):
template_name = "profile.html"
form_class = ProfileForm