[Answered ]-How can I prevent duplicate usernames, given that they are case sensitive by default?

1๐Ÿ‘

You could use a CustomUserManager and in the create_user() method, do a case insensitive check to see if the username is already present with iexact

๐Ÿ‘คEwan

1๐Ÿ‘

I think I have a solution:

def clean_username(self):
    kwargs = {
        '{0}__{1}'.format(UsernameField(), 'iexact'): self.cleaned_data['username'],
    }
    if User.objects.filter(**kwargs):
        raise ValidationError(_('A user with that username already exists.'), code='invalid')
    return self.cleaned_data['username']

UsernameField() is from django-registration-redux.

If there are any problems with this approach, please say!

๐Ÿ‘คStringsOnFire

0๐Ÿ‘

I do it with RegistrationFormCaseInsensitive form from django_registration (https://pypi.org/project/django-registration/)

After install:

In admin.py:

from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
    pass

Create forms.py with:

from django_registration.forms import RegistrationFormCaseInsensitive
from .models import CustomUser


class CustomUserForm(RegistrationFormCaseInsensitive):
    class Meta(RegistrationFormCaseInsensitive.Meta):
        model = CustomUser

in urls.py add one of this imports:
for one step registration:

from django_registration.backends.one_step.views import RegistrationView

or for registration with mail link:

from django_registration.backends.activation.views import RegistrationView

and then add the path:

path("accounts/register/",
     RegistrationView.as_view(
         form_class=CustomUserForm,
         success_url="/"
     ), name="django_registration_register"),
๐Ÿ‘คMarco Giuliani

Leave a comment