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

I am using bootstrap3 as the default template package in django_crispy_forms and trying to display a form with a crisp 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 submitting a form with errors, re-showing the template does not display errors, although I can print form._errors in the view and see a list of errors.

If I change helper.field_template to a different value (or delete it to set the default value), errors appear above each field, but I no longer get the built-in display.

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

+6
source share
2 answers

We use django.contrib.messages to push the common error line when the form has validation errors, and leave only field errors 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) 

Then we use bootstrap alerts to display all messages, including our common error, although you could, of course, mark it as you want.

But if all you want to do is move the errors to a separate block, add them to your query 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 play with the attributes of the crisp crystal shape and styles to control the display of inline errors.

+2
source

Perhaps the easier way is the following, because it uses less import ...

.. in the 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:

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

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

Crispy is a really smart system. The system knows how to intuitively display form errors.

+1
source

Source: https://habr.com/ru/post/954942/


All Articles