WholesomeGhost
WholesomeGhost

Reputation: 1121

Checking for duplicate email address causing Bad Request error

I have a form for creating new users and I've added clean_email function for checking if the email address already exists like this:

class NewUserForm(ModelForm):
    class Meta:
        model = Student
        fields = '__all__'
    
    def clean_email(self):
        email = self.cleaned_data.get('email')

        try:
            match = User.objects.get(email = email)
        except User.DoesNotExist:
            return email
        raise forms.ValidationError('User with this email address already exists.')

Unfortunately, after I try to test this by attempting to register a user with an email address that already exists I get the This page isn't working error in my browser. I'm not sure why this is happening, can anyone help?

Edit: I figured out what the problem was, now it sort of works. It doesn't allow me to create a user with the duplicate email address but how do I display the error message on the site?

Edit_2: View code

form = NewUserForm(request.POST)
if form.is_valid():
    data = form.cleaned_data
else:
    form = NewUserForm()
return redirect('newuserpage')

Upvotes: 0

Views: 169

Answers (1)

WholesomeGhost
WholesomeGhost

Reputation: 1121

There were some problems with my views. I fixed it like this:

form = NewUserForm(request.POST)
if form.is_valid():
    data = form.cleaned_data
else:
    return render(request, 'newuser.html',  {'form':form})
return redirect('newuserpage')

Upvotes: 1

Related Questions