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