Answer the question
In order to leave comments, you need to log in
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)
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question