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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With