from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] def clean_email(self): email = self.cleaned_data.get('email') if User.objects.filter(email__iexact=email).exists(): raise forms.ValidationError('An account with this email address already exists.') return email.lower() class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] def clean_email(self): email = self.cleaned_data.get('email') # Allow the current user to keep their own email if User.objects.filter(email__iexact=email).exclude(pk=self.instance.pk).exists(): raise forms.ValidationError('An account with this email address already exists.') return email.lower()