Thie is the source code in Django, when change the permission for a user named “xxx///\”, it will have an error, but in fact i don’t want to block this format username, so i want to overwrite the UserChangeForm class. Could you please tell me how to do this? Thanks!
class UserChangeForm(forms.ModelForm):
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.")})
password = ReadOnlyPasswordHashField(label=_("Password"),
help_text=_("Raw passwords are not stored, so there is no way to see "
"this user's password, but you can change the password "
"using <a href=\"password/\">this form</a>."))
def clean_password(self):
return self.initial["password"]
class Meta:
model = User
def __init__(self, *args, **kwargs):
super(UserChangeForm, self).__init__(*args, **kwargs)
f = self.fields.get('user_permissions', None)
if f is not None:
f.queryset = f.queryset.select_related('content_type')
I finally find the method,add this in the Admin.py
from django.contrib.auth.admin import UserAdmin
# overwrite the UserChangeForm
class UserChangeForm(forms.ModelForm):
username = forms.RegexField(
label=_("Username"), max_length=30, regex=r"^[a-zA-Z0-9@\.+-_\/\\]+$",
help_text = _("Required. 30 characters or fewer. Letters, digits and "
"@/./+/-/_ only."),
error_messages = {
'invalid': _("This value may contain only letters, numbers and "
".")})
UserAdmin.form = UserChangeForm
Thanks all the same
Your regex isn’t doing what you want. Find some tutorials on regex (google ‘Regex Tutorial’). Then I’d suggest getting some software to test regex (Regex Coach on windows is great).
I think the expression
^[a-zA-Z0-9@\.+-_\/\\]+$. Should do what you’re looking for. You’ll need to change your help and error text too – you’re actually accepting additional characters to the ones you say you’re accepting. Lastly, add amax_lengthfield to match your existing help text.EDIT
To override the UserChangeForm rewrite the class statement so your form inherits from UserChangeForm instead of ModelForm –
Have a look at the docs for more information on inheritance with Django forms.