10

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')
            )
        )

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.

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.

How can I use django-crispy-forms to display all errors of this form in a separate div for example?

4

3 回答 3

3

当表单出现验证错误时,我们使用 django.contrib.messages 推送一个通用错误字符串,并单独保留字段错误以内联呈现:

from django.contrib import messages
# ...
if not form.is_valid():
    messages.error(request, "Please correct the errors below and resubmit.")
    return render(request, template, context)

然后,我们使用引导警报来显示所有消息,包括我们的一般错误,尽管您当然可以随意标记它。

但是,如果您只想将错误移到单独的块中,请将它们添加到您的请求上下文中:

from django.contrib import messages
# ...
if not form.is_valid():
    context['form_errors'] = form.errors
    return render(request, template, context)

并在您的模板中:

{% crispy form %}
<div id='form-errors'>{{ form_errors }}</div>

然后,您可以使用脆表单的辅助属性和样式来控制内联错误的显示。

于 2014-04-10T15:01:22.710 回答
1

也许更简单的方法是下一个,因为它使用更少的进口......

.. 在意见中:

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})

...并以您只需要的形式:

{% load crispy_forms_tags %}
{% crispy form %}

...其中' url_name '是在urlpatterns(urls.py)中定义的模式名称......这就是你真正需要的......

Crispy 是一个非常智能的系统。系统知道如何直观地显示表单错误。

于 2014-06-04T07:45:03.167 回答
0

您可能需要考虑使用FormView通用视图,尤其是在您使用松脆表单时:

app/views.py

from django.views.generic.edit import FormView
from django.urls import reverse_lazy
from .forms import MyForm

class MyFormView(FormView):
    template_name = 'app/myform.html'
    form_class = MyForm
    success_url = reverse_lazy('success_url')

app/templates/app/myform.html

{% load crispy_forms_tags %}
{% crispy form %}
于 2021-12-13T17:03:21.713 回答