Django:使用小部件来限制 ModelForm 中的选择 [英] Django : Use widget to limit choices in a ModelForm
问题描述
我的模型表单继承自子系统表单.我想限制表单中用户的选择.(特别是名字)我知道我必须使用小部件.但它不起作用.
My model form inherit from subsystem form. I want to limit choices for the user in the form. (specially the name) I know I have to use widgets. But It doesn't work.
我必须使用 SubsytemForm.
I have to use SubsytemForm.
SUBSYSTEM_CHOICES = (a1,a2,a3)
class Subsystem(models.Model):
name = models.CharField("Name", max_length=20)
class SubsytemForm(forms.ModelForm):
class Meta:
model = Subsystem
widgets = {
'name': ChoiceField(widget=RadioSelect, choices=SUBSYSTEM_CHOICES)
}
推荐答案
来自 django 模型表单文档:
如果你像这样显式地实例化一个表单域,Django 假设你想完全定义它的行为;因此,默认属性(例如 max_length 或 required)不是从对应型号.如果要保持中指定的行为模型时,您必须明确设置相关参数声明表单域.
If you explicitly instantiate a form field like this, Django assumes that you want to completely define its behavior; therefore, default attributes (such as max_length or required) are not drawn from the corresponding model. If you want to maintain the behavior specified in the model, you must set the relevant arguments explicitly when declaring the form field.
你可以试试:
class SubsytemForm(forms.ModelForm):
name = forms.ChoiceField(widget=RadioSelect, choices= choices )
class Meta:
model = Subsystem
你也可以
class SubsytemForm(forms.ModelForm):
class Meta:
model = Subsystem
def __init__(self, *args, **kwargs):
self.name_choices = kwargs.pop('name_choices', None)
super(SubsytemForm,self).__init__(*args,**kwargs)
self.fields['name'].queryset= self.name_choices
并在 SubsytemForm
创建中将 name_choices
作为参数发送.请记住,选择应该是一个查询集.
and send name_choices
as parameter in SubsytemForm
creation. Remember that choices should be a query set.
另外,您应该阅读 如何过滤Django ModelForm 中的外键选择?
这篇关于Django:使用小部件来限制 ModelForm 中的选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!