我正在使用django-crispy-forms呈现Bootstrap3 inline form(代码如下所示),但表单提交时的错误(如跳过必填字段)未显示。它们以正常和横向形式布局。
有人可以建议可能的原因吗?
class Person(models.Model):
name = models.CharField(max_length=500)
city = models.CharField(max_length=50)
country = models.CharField(max_length=50)
email = models.EmailField(blank=True)
class EntryForm(forms.ModelForm):
class Meta:
model = Person
def __init__(self, *args, **kwargs):
super(EntryForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.form_class = 'form-inline'
self.helper.field_template = 'bootstrap3/layout/inline_field.html'
self.helper.layout.append(ButtonHolder(
Submit('save', 'Save', css_class='btn-primary btn-hg')
)
)
我在模板中使用{% load crispy_forms_tags %}
和{% crispy form %}
。
答案 0 :(得分:7)
原因是您使用的inline_field.html模板没有显示错误的代码。
请将正常bootstrap3 / field.html与内联版本进行比较。你会注意到
{% include 'bootstrap3/layout/help_text_and_errors.html' %}
后者缺少。将内联更改为下面的内容后,您将收到错误消息。
{% load crispy_forms_field %}
{% if field.is_hidden %}
{{ field }}
{% else %}
{% if field|is_checkbox %}
<div id="div_{{ field.auto_id }}" class="checkbox">
<label for="{{ field.id_for_label }}" class="{% if field.field.required %} requiredField{% endif %}">
{% crispy_field field 'class' 'checkbox' %}
{{ field.label|safe }}
{% include 'bootstrap3/layout/help_text_and_errors.html' %}
</label>
</div>
{% else %}
<div id="div_{{ field.auto_id }}" class="form-group">
<label for="{{ field.id_for_label }}" class="sr-only{% if field.field.required %} requiredField{% endif %}">
{{ field.label|safe }}
</label>
{% crispy_field field 'placeholder' field.label %}
{% include 'bootstrap3/layout/help_text_and_errors.html' %}
</div>
{% endif %}
{% endif %}
当然错误消息非常难看(因为它们来自正常版本),因此您可能必须创建bootstrap3/layout/help_text_and_errors.html
的内联版本。此外,可能还需要一些error
css类 - 请参阅field.html。
答案 1 :(得分:1)
以下是我项目的当前配置。我认为它也可能适合你。
#forms.py
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Div
from crispy_forms.bootstrap import FormActions
from myapp.models import Person
class EntryForm(forms.ModelForm):
class Meta:
model = Person
def __init__(self, *args, **kwargs):
super(EntryForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_id = 'id-entryform'
self.helper.form_class = 'form-inline'
self.helper.form.method = 'post'
self.helper.form.action = ''
self.helper.layout = Layout(
Div('name','email'),
Div('country','city'),
FormActions(Submit('save', 'Save', css_class='btn-primary btn-hg')
)
)