I want to post this here too to bring more light to this topic:
forms.py
from django import forms
from captcha.fields import CaptchaField, CaptchaTextInput
from django.forms.utils import ErrorList
from django.utils.safestring import mark_safe
class ContactForm(forms.Form):
first_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', "placeholder": "first name"}), required=True)
last_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', "placeholder": "last name"}), required=False)
from_email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control', "placeholder": "email"}), required=True)
subject = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', "placeholder": "subject"}), required=False)
message = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', "placeholder": "message"}), required=True)
captcha = CaptchaField(widget=CaptchaTextInput(attrs={'class': 'form-control', "placeholder": "prove u r not a bot đ"}), required=True, error_messages={'invalid': 'u are a bot đ¤'})
class DivErrorList(ErrorList):
def __str__(self):
return self.as_divs()
def as_divs(self):
if not self: return ''
return mark_safe('<div class="errorlist">%s</div>' % ''.join(['<div class="error">%s</div>' % e for e in self]))
views.py
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse
from django.shortcuts import render, redirect
from .forms import ContactForm, DivErrorList
from django.contrib import messages
def contactView(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST, auto_id=False, error_class=DivErrorList)
if form.is_valid():
subject = form.cleaned_data['subject']
body = {
'first_name': form.cleaned_data['first_name'],
'last_name': form.cleaned_data['last_name'],
'from_email': form.cleaned_data['from_email'],
'message': form.cleaned_data['message'],
}
message = "\n".join(body.values())
try:
send_mail(subject, message, 'hello@testy123.com', ['hello@testy123.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
messages.success(request, 'THANK YOU message received')
return redirect('home')
messages.error(request, form.errors)
return render(request, 'contact.html', {'form': form})
messages.html
{% for message in messages %}
<div class="alert {{ message.tags }} alert-dismissible fade show" role="alert">
{{ message }}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endfor %}
As you can see, the errors are still being wrapped in a list tagâŚ
I want it to be in a div onlyâŚ
What am I missing?