2

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?

  • do you want to change only **username** validation ?? – rahul.m Feb 03 '21 at 12:03
  • I want to change password validation too and if i figure out how to change username validation this will not be a problem –  Feb 03 '21 at 12:13
  • 1
    Check this question [How to customize username validation](https://stackoverflow.com/q/48030567/14991864). Also for password: [How to use custom password validators beside the django auth password validators?](https://stackoverflow.com/questions/43915518/how-to-use-custom-password-validators-beside-the-django-auth-password-validators) – Abdul Aziz Barkat Feb 03 '21 at 13:09

1 Answers1

4

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.

Moha369
  • 815
  • 7
  • 16