user13553080
user13553080

Reputation:

How to customize UserCreationForm validation in django

I'm currently trying to build user registration form using UserCreationForm but it doesn't suit my needs. First of all, Username field accepts not only alphabet symbols and digits but also @ . + - _. I want to make it accept only latin and cyrillic leterrs and digits but I could not find any information. Also i want to change it's other properties like maximum length. Also after we make these changes will both client and server sides validation process deny banned symbols?

Here is some code I already have in forms.py:

class CreateUserForm(UserCreationForm):
class Meta:
    model = User
    fields = ['username', 'email', 'password1', 'password2']

and views.py:

def register(request):
form = CreateUserForm()

if request.method == 'POST':
    form = CreateUserForm(request.POST)
    if form.is_valid():
        form.save()

context = {'form': form}
return render(request, 'register.html', context)

Also, is this default UserCreationForm relevant way to register user? Or it would be better if I write my own one?

Upvotes: 2

Views: 2013

Answers (1)

Moha369
Moha369

Reputation: 834

You have to know that UserCreationForm is basically a Django Form after all. So form validation mechanics applies on it.

As the docs mentions, you can validate a custom field by creating a method holding this name format: clean_<field name>, in your case its: clean_username.

This is a sample of a field clean method:

def clean_username(self):
    username = self.cleaned_data['username']
    # Do whatever you want
    if error_case: # Write your own error case.
        raise forms.ValidationError("Error Message") # Your own error message that will appear to the user in case the field is not valid
    return email # In case everything is fine just return user's input.

Upvotes: 5

Related Questions