Reputation: 19
I'm raising custom validation error in email field which accept only yahoo, gmail and outlook only. What am I doing wrong here?
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile, Testimonial
class UserUpdateForm(forms.ModelForm):
username = forms.CharField()
first_name = forms.CharField()
last_name = forms.CharField()
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'first_name', 'last_name']
def clean_email(self):
email = self.cleaned_data.get('email')
email_exists = User.objects.filter(email=email)
accepted_domains = ['gmail.com', 'yahoo.com', 'outlook.com', 'hotmail.com']
username = self.cleaned_data.get('username')
_, domain = email.split('@')
if email_exists.exists():
raise forms.ValidationError("Email is taken")
elif domain.lower() not in accepted_domains:
raise forms.ValidationError("Invalid email")
return email
Upvotes: 0
Views: 187
Reputation: 51988
You can do it like this:
accepted_domains = ['gmail.com', 'yahoo.com', 'outlook.com']
_, domain = email.split('@')
if email_exists.exists() and not self.instance and self.instance.pk==None:
raise forms.ValidationError("Email is taken")
if domain.lower() not in accepted_domains:
raise forms.ValidationError("Email should be gmail, yahoo and outlook only")
return email
Upvotes: 1