djangobootstrap-5django-crispy-forms

Duplicate validation message in Django contact form with Bootstrap 5 and Crispy Forms


I have a contact form in Django that I've styled using Bootstrap 5 and Crispy Forms. The form includes validations on fields, such as email validation and required fields.

The issue I'm facing is that the validation message is being duplicated on the page when an error occurs. For example, if I submit the form without filling in the email field, two identical error messages appear.

I've reviewed my code and templates multiple times, but I can't seem to find the cause of the duplication. Here's my relevant code:

[forms.py]

from crispy_bootstrap5.bootstrap5 import FloatingField
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Div, Submit
from django import forms
from django.core.validators import EmailValidator

class CustomSubmit(Submit):
    field_classes = "btn btn-outline-primary"

class FormularioContacto(forms.Form):
    nombre = forms.CharField(
        label='Nombre',
        max_length=50,
        required=True,
    )

    email = forms.EmailField(
        label='Email',
        required=True,
        validators=[EmailValidator()],
        error_messages={'invalid': 'Correo electrónico no válido'},
    )

    contenido = forms.CharField(
        label='Mensaje',
        widget=forms.Textarea(),
        required=False,
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'formularioContacto'
        self.helper.form_class = 'formulario'
        self.helper.form_method = 'post'
        self.helper.attrs = {'novalidate': True}  # Add 'novalidate' attribute to the form

        self.helper.layout = Div(
            Div(
                Div(
                    FloatingField('nombre'),
                    FloatingField('email'),
                    FloatingField('contenido'),
                    Div(
                        CustomSubmit('Enviar', 'submit', css_class='btn-lg'),
                        css_class='text-center mt-3'
                    ),
                    css_class='col-md-6 mx-auto'
                ),
                css_class='row'
            ),
            css_class='container my-4'
        )

[views.py]

import smtplib
from django.core.mail import EmailMessage
from django.shortcuts import render, redirect
from .forms import ContactForm

def contact(request):
    contact_form = ContactForm()

    if request.method == 'POST':
        contact_form = ContactForm(request.POST)
        if contact_form.is_valid():
            # Code to send the email

    return render(request, 'contact.html', {'form': contact_form})

[contact.html]

{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% load static %}

{% block content %}
    <div class="container">
        <form class="form" method="post">
            {% csrf_token %}
            <!-- Form fields and validation messages -->
        </form>
    </div>
{% endblock %}

enter image description here

I've also tried removing any custom CSS or JavaScript that could potentially interfere with the form validation, but the duplication issue persists.

I would appreciate any insights into what might be causing the duplication of the validation message and how to resolve it. Is there any specific configuration or code that I need to adjust in order to prevent the duplication?

Thank you for your assistance!


Solution

  • Just comment the email validator, your code will work as expected. Don't worry email validation will work.

    email = forms.EmailField(
        label='Email',
        required=True,
        # validators=[EmailValidator()],
        error_messages={'invalid': 'Correo electrónico no válido'},
    )