'How to customize the validation error message in Django?
I am trying to create a registration page in Django and to check fields validation. I wanna set a custom validation error message to the email field. Can you help me, please?
Here is the view.py:
from django.shortcuts import render
from django.http import HttpResponse, request
from django.db import connection
from django.contrib.auth.decorators import login_required
import pyodbc
def newUser(request):
form = NewUserFrom(request.POST or None)
if not form.is_valid():
context = {'frmNewUser':form}
return render(request,'login/newuser.html', context)
return render(request, "login/welcome.html")
Here is the forms.py:
from ctypes import alignment
from email import message
from urllib import request
from django import forms
class NewUserFrom(forms.Form):
error_css_class = 'error'
username = forms.CharField(max_length=50, widget=forms.TextInput, label="Username")
password = forms.CharField(widget=forms.PasswordInput, label="Password")
confirm_password = forms.CharField(label="Confirm password", widget=forms.PasswordInput)
name = forms.CharField(max_length=50, widget=forms.TextInput, label="Name")
email = forms.EmailField(max_length=50, widget=forms.EmailInput, label="Email")
def clean_password(self):
cleaned_data = super().clean()
pwd = cleaned_data.get('password')
cof_pwd = cleaned_data.get('confirm_password')
# if pwd and cof_pwd:
if pwd != cof_pwd:
raise forms.ValidationError('Password is not match.')
return cleaned_data
def clean(self):
cleaned_data = super(NewUserFrom,self).clean()
email = cleaned_data.get('email')
if email.strip() == "".strip():
# self.add_error('email','Email is reqiered.')
raise forms.ValidationError('Email is reqiered.')
else:
fistPart, secPart = str(email).split('@')
raise forms.ValidationError('Email error.')
Here is the NewUser.html:
{% block content %}
<form method="POST">
{% csrf_token %}
<table>
{{frmNewUser.as_table}}
{% for field in frmNewUser.fields %}
{% if field.errors %}
{% for error in field.errors %}
<p style="color: red;">{{error}}</p>
{% endfor %}
{% endif %}
{% endfor %}
</table>
<input type="submit" name="Save" value="Save" colspan=2>
</form>
{% endblock content %}
Solution 1:[1]
You havn't mentioned against what conditions you want to validate the email. Most of the checks for a normal email shall be done by django in-build validators since you are using forms.EmailField. But if you want to do further checks, then you can create another clean method specially for the email field. Just an example to get you started.
def clean_email(self):
email = self.cleaned_data.get('email')
domain = email.split('@')[1]
if (domain == 'gmail') or (domain == 'yahoo'):
raise forms.ValidationError('Please use your official email id.')
return email
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chandragupta Borkotoky |
