A
A
Anton Kuzmichev2014-05-22 13:55:53
Django
Anton Kuzmichev, 2014-05-22 13:55:53

How to change the regular expression by which username is checked when editing a user in the admin panel in Django?

The task is this: you need to allow the use of spaces in the username, since during social authorization a user with a nickname like "Ivan Ivanov" is created, but it is not possible to edit it later, when saving the form, it swears - "This value can consist of letters, numbers and @ signs /./+/-/_.".
Everywhere on the Internet, approximately the same recipe is given: create your own forms for adding and editing a user, and your own UserAdmin, and re-register it.
Well, I did it like this, in my admin.py:

username_regex_field = forms.RegexField(
    label=_("Username"),
    max_length=30,
    regex=r'^[\ \[email protected]+-]+$',
    help_text=_("Required. 30 characters or fewer. Letters, digits and "
                "@/./+/-/_ only."),
    error_messages={
        'invalid': _("This value may contain only letters, numbers and "
        "@/./+/-/_ characters.")})

class MyUserCreationForm(UserCreationForm):
    username = username_regex_field

class MyUserChangeForm(UserChangeForm):
    username = username_regex_field

class MyUserAdmin(UserAdmin):
    add_form = MyUserCreationForm
    form = MyUserChangeForm

admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)

This is minimal but working code.
But he does not solve the problem. When debugging, it turned out that when validating the form, in the django.core.validators.RegexValidator class, the username is checked first by my regular expression (the check succeeds), and then by the original Django one (of course, it does not pass)! I don’t understand where the old regular expression comes from if I redefined the form and the field in it.
I've already tried everything: I copied the source class code entirely, changing only the name, the ancestor class, and the regular expressions I needed - it still doesn't work. Moreover, wherever this method is given on the Internet, there are no comments anywhere on the topic that it does not work.
Used Django 1.6.5, my experience is almost half a year

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rostislav Grigoriev, 2014-05-22
@Assargin

Apparently, the validator also works when saved in the User
model itself. Accordingly, the solution may be to create the user model itself, inheriting the abstract standard model and redefining the username field validators in it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question