使用内联格式呈现django-crispy-forms中的字段错误 [英] Rendering field errors in django-crispy-forms with inline forms
问题描述
我使用bootstrap3作为django_crispy_forms中的默认模板包,并尝试使用脆性标签来呈现一个表单:
I'm using bootstrap3 as the default template pack in django_crispy_forms, and trying to render a form with the crispy tag:
{% crispy form %}
我的表单类具有以下帮助器属性:
My form class has the following helper attributes:
class TheForm(forms.Form):
adv_var = forms.CharField(label="variable", max_length=70)
value = forms.FloatField()
def __init__(self, *args, **kwargs):
super(TheForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'post'
self.helper.form_class = 'form-inline'
self.helper.field_template = 'bootstrap3/layout/inline_field.html'
self.helper.layout = Layout(
'adv_var', 'value',
ButtonHolder(
Submit('submit', 'Start', css_class='button white')
)
)
当发布表单错误时,重新呈现模板不会显示错误,即使我可以在视图中打印form._errors并查看错误列表。
When posting the form with errors, re-rendering the template does not show the errors even though I can print form._errors in the view and see the list of errors.
如果我将helper.field_template更改为另一个值(或将其删除以设置默认值)错误显示在每个字段之上 - 但是我不再获得内联显示。
If I change the helper.field_template to another value (or remove it to set the default) the errors are displayed above each field - but I don't get the inline display anymore.
如何使用django-crispy-forms来显示此表单的所有错误一个单独的div例如?
How can I use django-crispy-forms to display all errors of this form in a separate div for example?
推荐答案
也许更容易的方法是下一个,因为它使用较少的导入...
Maybe the easier way is the next because it uses less imports...
..在视图中:
if request.method == 'POST':
form = TheForm(request.POST)
if form.is_valid():
form.save()
return redirect('url_name')
else:
form = TheForm()
return render(request, 'form.html', {'form': form})
...并且您只需要的形式:
... and in the form you need only:
{% load crispy_forms_tags %}
{% crispy form %}
...其中' url_name '是urlpatterns(urls.py)中定义的模式名称...这就是你真正需要的...
... where 'url_name' is defined name of pattern in urlpatterns (urls.py )... that's all you need really...
Crispy是一个非常聪明的系统。系统知道如何直观地显示表单错误。
Crispy is a really smart system. The system knows how can intuitively to show the form errors.
这篇关于使用内联格式呈现django-crispy-forms中的字段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!