I feel rather stupid for asking this but I'll do it anyway. The 'Users' API reference in the Django documentation "User authentication in Django" (v. 1.4) says that a username may only contain letters, digits, and the characters @, +, ., -, and _. Yet I can go into the Python shell and do the following:
>>> from django.contrib.auth.models import User
>>> u = User.objects.create_user('joe#')
Why doesn't this raise an exception? I looked at the source code in ../contrib/auth/models.py and it doesn't appear to be flagging invalid characters. What's going on here? It would appear that if you want to catch an erroneous username, you'd have to do it via form validation.
I guess the developers wanted to provide application developers with the flexibility so, that we could store special symbols. So, instead of validating the inputs at the model level, it is done in the form. You can find the form inside django.contrib.auth.form.UserCreationForm
The snippet is here:
You can see the validation using Regular Expression on the Username field.
class UserCreationForm(forms.ModelForm):
"""
A form that creates a user, with no privileges, from the given username and
password.
"""
error_messages = {
'duplicate_username': _("A user with that username already exists."),
'password_mismatch': _("The two password fields didn't match."),
}
username = forms.RegexField(label=_("Username"), max_length=30,
regex=r'^[\w.@+-]+$',
help_text = _("Required. 30 characters or fewer. Letters, digits and "
"@/./+/-/_ only."),
error_messages = {
'invalid': _("This value may contain only letters, numbers and "
"@/./+/-/_ characters.")})
password1 = forms.CharField(label=_("Password"),
widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"),
widget=forms.PasswordInput,
help_text = _("Enter the same password as above, for verification."))
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