ModelForm based on User allows any username without checking

54 views
Skip to first unread message

Bastian

unread,
Apr 4, 2012, 10:36:41 AM4/4/12
to django...@googlegroups.com
Hi,

I have a form that asks the registering user to choose a username. That form is a ModelForm based on the django.contrib.auth.models Users:

class usernameForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('username', )

The strange thing is that when it appears on the page it comes with the warning that says no more than 30 characters... but it actually does not check anything. I tried to enter whatever username, with spaces and () and in the view when I ask if form.is_valid() it returns True all the time!

Obviously this must be a mistake on my side somewhere but on such a simple setup I don't see where I am wrong, any idea welcome.

Pavan Verma

unread,
Apr 5, 2012, 1:51:14 PM4/5/12
to Django users
Hi Bastian,
you need to define the restrictions on the username field. It can be
done by including the code below inside usernameForm. This code is
from django/contrib/auth/forms.py -> UserCreationForm, you can refer
it to understand further.

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."})

thanks,
-pavan

Bastian

unread,
Apr 9, 2012, 3:53:55 PM4/9/12
to django...@googlegroups.com
Yes that's what I ended up doing but isn't it supposed to be automatic, coming from the restrictions of the model since it's a ModelForm?

Pavan Verma

unread,
Apr 10, 2012, 2:51:18 AM4/10/12
to Django users
I went through django/contrib/auth/models.py to check the definition
of the User model. I don't see this file defining any restrictions on
what a username can be. So, I think the form is the place (and
possibly the only place) which defines and enforces restrictions on
what the username can be.

Interestingly, the help_text for User.username is the following:

help_text=_('Required. 30 characters or fewer. Letters,
numbers and '
'@/./+/-/_ characters'))

But this restriction in neither defined nor enforced in the User model
class.


> isn't it supposed to be automatic, coming from the restrictions of the model since it's a ModelForm?

I didn't understand this comment. Why would you think ModelForm has
anything to do with it? As in, why would ModelForm know anything about
User.username.


thanks,
-pavan

Bastian

unread,
Apr 10, 2012, 7:03:42 AM4/10/12
to django...@googlegroups.com
I assumed restrictions would apply at model level but it's not the case.

About the ModelForm, isn't it the point of using a ModelForm? (with the User model as shown in the example of course) that it inherits from the model and automatically creates the right fields, widgets, and restrictions?

regards,
Bastian
Reply all
Reply to author
Forward
0 new messages