0

I'm trying to change these error messages to custom, here's code:

>>>forms.py
class UserRegistrationForm(forms.ModelForm):
    ...
    ...
    ...
    def clean_email(self):
        username = self.cleaned_data['username']
        email = self.cleaned_data['email']
        users = User.objects.filter(email__iexact=email).exclude(username__iexact=username)
        if users:
            raise forms.ValidationError("Email's already taken.")
        return email.lower()

    def clean_username(self):
        username = self.cleaned_data['username']
        try:
            user = User.objects.exclude(pk=self.instance.pk).get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError("Username's already taken.")

When I type username that is already taken I get an error screen:

KeyError at /account/register/
'username'
Request Method: POST
Request URL: http://127.0.0.1:8000/account/register/
Django Version: 3.1.1
Exception Type: KeyError
Exception Value: 'username'
Exception Location: C:\Users\user\Desktop\esh\myshop\account\forms.py, line 58, in clean_email

And also I can't figure out how to override invalid email error message.

amshinski
  • 174
  • 11

1 Answers1

0

Answer is:

    def clean_email(self):
        email = self.cleaned_data['email']
        users = User.objects.filter(email__iexact=email)
        if users:
            raise forms.ValidationError("Custom text about email.")
        return email.lower()

    def clean_username(self):
        username = self.cleaned_data['username']
        users = User.objects.filter(username__iexact=username)
        if users:
            raise forms.ValidationError("Custom text about username.")
        return username

I tested it and it works perfectly.

amshinski
  • 174
  • 11