user13553080
user13553080

Reputation:

Django AttributeError 'CreateUserForm' object has no attribute 'username'

I am trying to create user registration page, to do so, I use default UserCreationForm. I want to register users through their phone numbers, so I changed this form like this:

class CreateUserForm(UserCreationForm):
    restriction = RegexValidator(r'^[0-9]*$')
    username = forms.CharField(max_length=11, validators=[restriction])
    class Meta:
        model = User
        fields = ['username', 'first_name', 'password1', 'password2']

There is part of registration view function:

if form.is_valid():
    #save form and redirect
elif len(form.cleaned_data['password1']) < 8:
    messages.error(request, 'Password is too short')
elif form.cleaned_data['username'].isnumeric() == False:
    messages.error(request, 'Enter valid phone number!')

So if the form turns out to be invalid, it checks whether password or phone number is wrong but when it comes to checking phone, it returns "KeyError at /registration/" and "Exception Value: 'username'". If I change form.cleaned_data['username'] to form.username, it returns "Django AttributeError 'CreateUserForm' object has no attribute 'username'"

I genuinely don't know what to do and why this error is even a thing.

Upvotes: 0

Views: 794

Answers (1)

user13553080
user13553080

Reputation:

As Abdul Aziz Barkat said,

form.cleaned_data.get('username', '')

actually is the solution.

Upvotes: 1

Related Questions