我们有一个清脆的表单,我们希望能够在表单HTML
模板的不同部分呈现不同的字段,但是我们无法在Crispy Documentation中找到这样做的方法。下面是一些稍微简化的代码,用于说明我们要做的事情:
forms.py
helper = FormHelper()
helper.layout_1 = Layout(
Div(
Field('field_1a'),
Field('field_1b')
)
)
helper.layout_2 = Layout(
Div(
Field('field_2a'),
Field('field_2b')
)
)
template.html
<body>
{% crispy form layout_1 %}
<!-- A big bunch of other html -->
{% crispy form layout_2 %}
</body>
有没有人知道实现这一目标的干净方法?
到目前为止我们已经看过的方法必须排除:
choice
字段,其选项以编程方式确定。crispy.forms.layout.HTML
对象来包含HTML,它将我们布局的两个不同部分分开。但是,有很多HTML,如果我们将它直接嵌入到python中,就很难维护。答案 0 :(得分:15)
更新:这不适用于forms.ModelForm
尝试创建两个帮助程序而不是两个布局,然后显式调用单独的帮助程序。这样做,你必须手动编写<form>
标签,将两个表格都包含在你的模板中,但希望能提供你需要的解决方案。
forms.py
class Form(forms.Form):
field_1a = forms.CharField()
field_1b = forms.CharField()
field_2a = forms.CharField()
field_2b = forms.CharField()
def __init__(self, *args, **kwargs):
super(Form, self).__init__(*args, **kwargs)
helper1 = FormHelper()
helper1.form_tag = False
helper1.layout = Layout(
Div(
Field('field_1a'),
Field('field_1b')
)
)
helper2 = FormHelper()
helper2.form_tag = False
helper2.disable_csrf = True
helper2.layout = Layout(
Div(
Field('field_2a'),
Field('field_2b')
)
)
然后在你的模板中:
<body>
<form>
{% crispy form form.helper1 %}
<!-- A big bunch of other html -->
{% crispy form form.helper2 %}
</form>
</body>
答案 1 :(得分:1)
创建一个form.py
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Field,Layout, ButtonHolder, Submit
class layout1Form(forms.Form):
def __init__(self, *args, **kwargs):
super(layout1Form, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.layout = Layout(
Field('answer',css_class="field span8"),
ButtonHolder(
Submit('submit', 'Submit', css_class='btn-primary pull-right')
)
)
self.helper.form_tag = False
class layout2Form(forms.Form):
def __init__(self, *args, **kwargs):
super(layout1Form, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.layout = Layout(
Field('answer',css_class="field span8"),
ButtonHolder(
Submit('submit', 'Submit', css_class='btn-primary pull-right')
)
)
self.helper.form_tag = False
然后在views.py
中from ...forms import layout1Form,layout2Form
def layouttest(request):
form = layout1Form(request.POST)
form1=layout2Form(request.POST)
return render(request,'test.html',{'frm1':form,'frm2':form1})
然后在模板中,您可以在
中使用<form id="signup" class="form-horizontal" method="post" action="">
{% crispy frm1 %}
""the big html""
{% crispy frm2 %}
<button type="submit" class="btn btn-success">Submit</button>
</form>