Rendering field errors in django-crispy-forms with inline forms

六月ゝ 毕业季﹏ 提交于 2019-12-05 03:56:37

We use django.contrib.messages to push a generic error string when the form has validation errors, and leave the field errors alone to render inline:

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)

We then use bootstrap alerts to show all messages, including our generic error, though you could of course mark it up however you wanted.

But if all you want to do is move the errors into a separate block, add them to your request context:

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

and in your template:

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

You can then fiddle with the crispy form's helper attributes and styles to control the display of the inline errors.

slaff.bg

Maybe the easier way is the next because it uses less imports...

.. in views:

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

... where 'url_name' is defined name of pattern in urlpatterns (urls.py )... that's all you need really...

Crispy is a really smart system. The system knows how can intuitively to show the form errors.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!