在Django联系表单中使用Bootstrap 5和Crispy Forms出现了重复的验证消息。

huangapple go评论59阅读模式
英文:

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

问题

我在Django中有一个联系表单,使用Bootstrap 5和Crispy Forms进行样式设置。表单包括对字段的验证,如电子邮件验证和必填字段。

我面临的问题是当发生错误时,验证消息在页面上被重复显示。例如,如果我提交表单而不填写电子邮件字段,会出现两条相同的错误消息。

我已经多次审查了我的代码和模板,但似乎找不到重复的原因。以下是我相关的代码:

[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 FormularioContacto

def contact(request):
    contact_form = FormularioContacto()

    if request.method == 'POST':
        contact_form = FormularioContacto(request.POST)
        if contact_form.is_valid():
            # 发送电子邮件的代码

    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>
    </div>
{% endblock %}

我也尝试删除任何可能干扰表单验证的自定义CSS或JavaScript,但重复的问题仍然存在。

我会感激您对可能导致验证消息重复出现以及如何解决这个问题的任何见解。是否需要调整特定的配置或代码以防止重复?

感谢您的帮助!

英文:

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 = &quot;btn btn-outline-primary&quot;

class FormularioContacto(forms.Form):
    nombre = forms.CharField(
        label=&#39;Nombre&#39;,
        max_length=50,
        required=True,
    )

    email = forms.EmailField(
        label=&#39;Email&#39;,
        required=True,
        validators=[EmailValidator()],
        error_messages={&#39;invalid&#39;: &#39;Correo electr&#243;nico no v&#225;lido&#39;},
    )

    contenido = forms.CharField(
        label=&#39;Mensaje&#39;,
        widget=forms.Textarea(),
        required=False,
    )

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

        self.helper.layout = Div(
            Div(
                Div(
                    FloatingField(&#39;nombre&#39;),
                    FloatingField(&#39;email&#39;),
                    FloatingField(&#39;contenido&#39;),
                    Div(
                        CustomSubmit(&#39;Enviar&#39;, &#39;submit&#39;, css_class=&#39;btn-lg&#39;),
                        css_class=&#39;text-center mt-3&#39;
                    ),
                    css_class=&#39;col-md-6 mx-auto&#39;
                ),
                css_class=&#39;row&#39;
            ),
            css_class=&#39;container my-4&#39;
        )
[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 == &#39;POST&#39;:
        contact_form = ContactForm(request.POST)
        if contact_form.is_valid():
            # Code to send the email

    return render(request, &#39;contact.html&#39;, {&#39;form&#39;: contact_form})

[contact.html]

{% extends &#39;base.html&#39; %}
{% load crispy_forms_tags %}
{% load static %}

{% block content %}
    &lt;div class=&quot;container&quot;&gt;
        &lt;form class=&quot;form&quot; method=&quot;post&quot;&gt;
            {% csrf_token %}
            &lt;!-- Form fields and validation messages --&gt;
        &lt;/form&gt;
    &lt;/div&gt;
{% endblock %}

在Django联系表单中使用Bootstrap 5和Crispy Forms出现了重复的验证消息。

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!

答案1

得分: 1

只需注释掉电子邮件验证器,您的代码将按预期工作。不用担心,电子邮件验证将正常工作。

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

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

email = forms.EmailField(
    label=&#39;Email&#39;,
    required=True,
    # validators=[EmailValidator()],
    error_messages={&#39;invalid&#39;: &#39;Correo electr&#243;nico no v&#225;lido&#39;},
)

huangapple
  • 本文由 发表于 2023年7月14日 04:50:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76683154.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定