When writing a user registration form in Django, you are likely to encounter this error message:
A user with that Username already exists.
This happens when a new user wants to register with a name that is already stored in the database. The message itself is self explainatory but what I need is to display this message in Chinese. According to Django's documentation, I should be able to do this:
class RegistrationForm(ModelForm):
class Meta:
model = User
error_messages = {
'unique': 'my custom error message',
}
But this didn't work. It turns out that Django's CharField only accepts the following error message keys:
Error message keys: required, max_length, min_length
Thanks to this StackOverflow post, here is how Django developers solved this problem in the UserCreationForm, we can adopt their solution to this situation:
class RegistrationForm(ModelForm):
# create your own error message key & value
error_messages = {
'duplicate_username': 'my custom error message'
}
class Meta:
model = User
# override the clean_<fieldname> method to validate the field yourself
def clean_username(self):
username = self.cleaned_data["username"]
try:
User._default_manager.get(username=username)
#if the user exists, then let's raise an error message
raise forms.ValidationError(
self.error_messages['duplicate_username'], #user my customized error message
code='duplicate_username', #set the error message key
)
except User.DoesNotExist:
return username # great, this user does not exist so we can continue the registration process
Now when you try to enter a duplicate username, you will see the custom error message being shown instead of the default one :)