如何根据在模型级别定义的枚举字段在 Django Modelform 中呈现单选按钮选择?
Posted
技术标签:
【中文标题】如何根据在模型级别定义的枚举字段在 Django Modelform 中呈现单选按钮选择?【英文标题】:How to render a radio button choice in Django Modelform based on enum field defined at the model level? 【发布时间】:2020-03-16 03:45:43 【问题描述】:我在模型级别定义了一个枚举字段(“类型”),如下所示,我应该如何在我的模型字段中实现相应的 ModelForm 字段?实际上,呈现的 html 代码不会输出单选按钮,而是将此字段包装在一个空列表中。是否应该“复制”表单类中的枚举选项以填充单选按钮选项,是否还有其他方法可以利用模型级别已经定义的选项?
呈现的 HTML
<div class="form-group">
<label for="id_type_0">Type</label>
<ul id="id_type" class="form-control">
</ul>
</div>
models.py
class Foo(models.Model):
name = models.CharField(max_length=50, blank=False, null=False)
TYPE_LIST = [
('EXT_CL', 'Customer'),
('INT_TP', 'Internal third party'),
('INT_OW', 'Owner'),
]
type = models.CharField(max_length=6, choices=TYPE_LIST,default='EXT_CL')
class Meta:
managed = True
db_table = 'foos'
fields = ('name','type')
def __str__(self):
object_name = self.name
return object_name
forms.py
class FooCreateForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.label_suffix = ''
self.fields['name'] = forms.CharField(label='Name',widget=forms.TextInput(attrs= 'class': 'form-control' ))
self.fields['type'] = forms.ChoiceField(label='Type',required=True,widget=forms.Radioselect(attrs= 'class': 'form-control' ))
class Meta(object):
model = Foos
fields = ('name','type')
def clean_name(self):
name = self.cleaned_data['name']
return name
def clean_type(self):
type = self.cleaned_data['type']
return type
template.html
<form id="foo-create-form" method="post" action=" " role="form">
% csrf_token %
<div class="form-group">
foo_create_form.name.label_tag
foo_create_form.name
</div>
<div class="form-group">
foo_create_form.type.label_tag
foo_create_form.type
</div>
</form>
【问题讨论】:
【参考方案1】:您应该在forms.py
而不是models.py
中设置选项
class FooCreateForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.label_suffix = ''
TYPE_LIST = [
('EXT_CL', 'Customer'),
('INT_TP', 'Internal third party'),
('INT_OW', 'Owner'),
]
self.fields['name'] = forms.CharField(label='Name',widget=forms.TextInput(attrs= 'class': 'form-control' ))
self.fields['type'] = forms.ChoiceField(label='Type',choice=TYPE_LIST, required=True,widget=forms.RadioSelect(attrs= 'class': 'form-control' ))
class Meta(object):
model = Foos
fields = ('name','type')
def clean_name(self):
name = self.cleaned_data['name']
return name
def clean_type(self):
type = self.cleaned_data['type']
return type
【讨论】:
以上是关于如何根据在模型级别定义的枚举字段在 Django Modelform 中呈现单选按钮选择?的主要内容,如果未能解决你的问题,请参考以下文章
如何将单个枚举用于 django 模型和 graphql 突变参数?
在 Django 模型中使用 save() 会产生 TypeError