Django:使用小部件来限制ModelForm中的选择 [英] Django : Use widget to limit choices in a ModelForm
问题描述
我想限制窗体中用户的选择。 (特别是名字)
我知道我必须使用小部件。但是它不起作用。
我必须使用SubsytemForm。
SUBSYSTEM_CHOICES =(a1,a2,a3)
类子系统(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模型表单文档:
< blockquote>
如果您明确地实例化了一个这样的表单域,Django假定你要完全定义其行为的
;因此,默认
属性(如max_length或必需)不是从
对应的模型中绘制的。如果要维护
模型中指定的行为,则必须在
声明表单域时显式设置相关参数。
您可以尝试:
class SubsytemForm(forms.ModelForm):
name = forms .ChoiceField(widget = RadioSelect,choices = choices)
class Meta:
model = Subsystem
另外你可以
class SubsytemForm(forms.ModelForm):
class Meta:
$ =
self.name_choices = kwargs.pop('name_choices',None)
super(SubsytemForm,self).__初始化__(self,* args,** kwargs) (* args,** kwargs)
self.fields ['name']。queryset = self.name_choices
并在 SubsytemForm
创建中发送 name_choices
作为参数。请记住,选择应该是一个查询集。
另外,您应该阅读如何在Django ModelForm中过滤ForeignKey选项?
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.
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)
}
From django model forms documentation:
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.
You can try with:
class SubsytemForm(forms.ModelForm):
name = forms.ChoiceField(widget=RadioSelect, choices= choices )
class Meta:
model = Subsystem
Also you can
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
and send name_choices
as parameter in SubsytemForm
creation. Remember that choices should be a query set.
Also, you should read How do I filter ForeignKey choices in a Django ModelForm?
这篇关于Django:使用小部件来限制ModelForm中的选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!