我有一个ModelForm,MyForm。帮我写一个方法,为表单中存在的每个字段返回html元素。
class MyForm(forms.ModelForm):
priority = forms.ChoiceField(
widget=forms.Select(attrs={'class': 'form-control','data-role':'select'}),
choices=((1,1), (2,2), (3,3), (4,4)),
required=True,
initial='3',
label=_('Priority'),
help_text=_("Please select a priority carefully. If unsure, leave it as '3'."),
)
due_date = forms.DateTimeField(
widget=forms.TextInput(attrs={'class': 'form-control','data-role':'datepicker'}),
required=False,
)
def getFormHtml(self):
#need to return a dictionary with the key being the form field name and value being the HTML tag for the respective element
答案 0 :(得分:0)
my_form = MyForm()
django具有内置的呈现表单的方法,您还可以在如下视图中获取表单的默认呈现:
my_form.as_p()
或
myform_as_table()
因此您可以扩展MyForm对象,使其具有从给定的表单实例以html格式返回表单的方法:
class MyForm(forms.ModelForm):
priority = forms.ChoiceField(
widget=forms.Select(attrs={'class': 'form-control','data-role':'select'}),
choices=((1,1), (2,2), (3,3), (4,4)),
required=True,
initial='3',
label=_('Priority'),
help_text=_("Please select a priority carefully. If unsure, leave it as '3'."),
)
due_date = forms.DateTimeField(
widget=forms.TextInput(attrs={'class': 'form-control','data-role':'datepicker'}),
required=False,
)
def getFormHtml(self):
return self.as_table()
当然,仅当您需要在其他视图中使用表单的html时,这才有意义。如果您需要模板中表单的html,则可以通过在模板中添加{{my_form.as_table}}
或render the form fields manually in the template
答案 1 :(得分:0)
提交后,您将使用元素的“名称”属性获得字段值。您可以获取表单方法(发布/获取),但html标签不会将其添加到视图中。