英文:
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 = "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 %}
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='Email',
required=True,
# validators=[EmailValidator()],
error_messages={'invalid': 'Correo electrónico no válido'},
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论