How to style the validation error list display by changing the error class by overwriting built-in form templates. error_class errorlist ErrorList

I couldn't find an up-to-date answer, so I'll write my own solution based on the Django documentation https://docs.djangoproject.com/en/4.2/ref/forms/api/#how-errors-are-displayed.

Explain: I override built-it templates of ErrorList using TemplatesSetting() which refers to the template engine. Now I can change HTML in custom templates.

from django.forms.renderers import TemplatesSetting
from django.forms.utils import ErrorList 

class CustomErrorList(ErrorList):
    def __init__(self, initlist=None, error_class=None, renderer=None):
        super().__init__(initlist, error_class="list-group", renderer=TemplatesSetting())

    template_name = "forms/errors/default.html"
    template_name_text = "forms/text.txt"
    template_name_ul = "forms/errors/ul.html"


class OfferForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.error_class = CustomErrorList

    class Meta:
        model = Offer
        exclude = ['city', 'user', 'is_active', 'count_of_views', 'in_favorites']



 in settings.py:
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates/')],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]

 in ul.html:
{% if errors %}<ul class="list-group">{% for error in errors %}<li class="list-group-item text-white bg-danger">{{ error }}</li>{% endfor %}</ul>{% endif %}
Back to Top