如何在Django Modelform中基于在模型级别定义的枚举字段呈现单选按钮选项



我在模型级别定义了一个枚举字段("type"(,如下所示,我应该如何在模型字段中实现相应的ModelForm字段?实际上,呈现的HTML代码不输出单选按钮,而是将该字段封装在一个空列表中。为了填充单选按钮选项,是否应该在表单类中"复制"枚举选项,是否还有其他选项可以利用已经在模型级别定义的选项?

渲染HTML

<div class="form-group">
<label for="id_type_0">Type</label>
<ul id="id_type" class="form-control">
</ul>
</div>  

型号.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 

表单.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>

您应该在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

相关内容

  • 没有找到相关文章

最新更新