Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enforcing lowercase usernames in Django

Tags:

django

Currently, in django.contrib.auth, there can be two users with the username 'john' and 'John'. How can I prevent this from happening.

The most straightforward approach is add a clean method in contib.auth.models and convert it to a lowercase before saving but i dont want to edit the contrib.auth package.

Thanks.

like image 444
nknj Avatar asked Sep 08 '25 08:09

nknj


2 Answers

Listen on pre_save for the Users model and then do your checks there. Least intrusive and most portable way.

Here is an example on how this would look like (adapted from the user profile example):

def username_check(sender, instance, **kwargs):
    if User.objects.filter(username=instance.username.lower()).count():
       raise ValidationError('Duplicate username')

pre_save.connect(username_check, sender=User)
like image 148
Burhan Khalid Avatar answered Sep 10 '25 02:09

Burhan Khalid


I have used clean method in the user creation form by extending the class UserCreationForm in my custom CustomerRegistrationForm.

The code for the same is as follows:

class CustomerRegistrationForm(UserCreationForm):
    # All your form code comes here like creating custom field, etc..
    
    ......
    ......
    ......
    ......


    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

    ......
    ......
    ......
    ......


    # This is the main centre of interest
    # We create the clean_username field specific cleaner method in order to get and set the required field data
    # In this case, the username field
    def clean_username(self):
        username = self.cleaned_data.get('username')  # get the username data
        lowercase_username = username.lower()         # get the lowercase version of it

        return lowercase_username

This approach is best as we'll not have to write extra messy code for pre_save event in database, and also, it comes with all django validator functionalities like duplicate username check, etc.

Every other thing will be automatically handled by django itself.

Do comment if there needs to be any modification in this code. T

like image 22
Charitra Agarwal Avatar answered Sep 10 '25 03:09

Charitra Agarwal