要将提交按钮添加到您的表单中,crispy_form 的文档是这样做的:
import floppyforms.__future__ as forms # you can use django's own ModelForm here
from crispy_forms.helper import FormHelper
from django.core.urlresolvers import reverse_lazy
class YourForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(YourForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'post' # this line sets your form's method to post
self.helper.form_action = reverse_lazy('your_post_url') # this line sets the form action
self.helper.layout = Layout( # the order of the items in this layout is important
'field1_of_your_model', # field1 will appear first in HTML
'field2_of_your_model', # field2 will appear second in HTML
# this is how to add the submit button to your form and since it is the last item in this tuple, it will be rendered last in the HTML
Submit('submit', u'Submit', css_class='btn btn-success'),
)
class Meta:
model = YourModel
然后,在你的模板中,你所要做的就是这个
{% load crispy_forms_tags %}
{% crispy form %}
就是这样。无需在模板中编写任何 html。
我认为crispy_forms 的全部意义在于用Python 定义HTML。这样您就不必在模板中编写太多 HTML。
一些补充说明:
由于您使用的是引导程序。在上面定义的__init__() 中还有另外三个对您有帮助的字段,如果需要,请添加:
self.helper.form_class = 'form-horizontal' # if you want to have a horizontally layout form
self.helper.label_class = 'col-md-3' # this css class attribute will be added to all of the labels in your form. For instance, the "Username: " label will have 'col-md-3'
self.helper.field_class = 'col-md-9' # this css class attribute will be added to all of the input fields in your form. For isntance, the input text box for "Username" will have 'col-md-9'