crispy_forms

I installed django-crispy-forms in the following way:

In the terminal

python3 -m pip install django-crispy-forms
python3 -m pip install crispy-bootstrap5

In settings.py

INSTALLED_APPS = [
    …
    # Third-party
    'crispy_forms',
    'crispy_bootstrap5',
    # Local
    …
]

# django-crispy-forms
CRISPY_ALLOWED_TEMPLATE_PACKS = 'bootstrap5'
CRISPY_TEMPLATE_PACK = 'bootstrap5'

In the template:

{% load crispy_forms_tags %}

<form class="" action="" method="post">
  {% csrf_token %}
  {{ form|crispy }}
</form>

If a form doesn’t validate Django either adds the

<p id="" class="invalid-feedback"></p>

to the form, or it doesn’t add the tag above, and just displays the browser default for the first field that doesn’t validate, a tool-tip that disappears the moment you scroll up or down.

I made a list of the forms showing the <p></p> and it turned out that all these forms have the following line of code in the __init__ method

class OpeningHourForm(ModelForm):
    class Meta:
        model = models.OpeningHour
        fields = ()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.use_required_attribute = False

The documentation I read about crispy_forms don’t mention this setting. Did I overlook something?

Kind regards,

Johanna

The use_required_attribute form attribute is a normal Django form setting, it’s not a part of crispy.

use_required_attribute seemed to solve this issue. However, now that I found the cause of the problem, I found a better fix:

<form class="" action="" method="post" novalidate>

Kind regards,
Johanna

1 Like