提交按钮不再适用于 django crispy 表单

Submit button no longer works with django crispy forms

我已将 bootstrap 添加到我的页面并尝试让 django crispy forms 工作。实际上,我所做的只是 pip install django-crispy-forms,将 crispy_forms 添加到 INSTALLED_APPS 并在我的模板中将 {{ form }} 更改为 {% crispy form %}(在添加 bootstrap 和jquery 到我的静态目录):

{% load crispy_forms_tags %}

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="." method="post">
{% csrf_token %}
{% crispy form %}
<input type="submit" value="Submit" class="btn btn-success">
</form>

这个表格过去工作得很好。更改后它看起来好多了,但是 提交按钮不再执行任何操作,因为它被移到了表单之外:

看到模板更改影响了文档其余部分的布局,我感到很惊讶。我做错了什么还是这是一个错误?

Django 1.8.1,django-crispy-forms 1.4.0

由于您自己在模板中包含表单标签、csrf 令牌和提交按钮,因此您应该使用 crispy filter 而不是 crispy 标签。

<form action="." method="post">
    {% csrf_token %}
    {{ form|crispy }}
    <input type="submit" value="Submit" class="btn btn-success">
</form>

如果你想使用标签,那么你可以在 FormHelper 中定义你的提交按钮。有关详细信息,请参阅 crispy tag docs

要将提交按钮添加到您的表单,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。


一些补充说明:

因为您正在使用 bootstrap。在上面定义的 __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'

对于那些使用标签卡在此处并希望将一些自定义 html 添加到他们的 <form>...

的其他人

您可以将 self.helper.form_tag = False 属性 添加到您的助手,它不会将 </form> 附加到您的表单末尾。

更多文档 here.