1

Thie是Django中的源代码,当更改名为“xxx///\”的用户的权限时,会出错,但实际上我不想阻止这种格式的用户名,所以我想覆盖UserChangeForm 类。你能告诉我怎么做吗?谢谢!

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')

我终于找到了方法,在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

一样的谢谢

4

1 回答 1

0

你的正则表达式没有做你想做的事。查找一些关于正则表达式的教程(谷歌“正则表达式教程”)。然后我建议使用一些软件来测试正则表达式(Windows 上的Regex Coach很棒)。

我觉得表情^[a-zA-Z0-9@\.+-_\/\\]+$。应该做你正在寻找的东西。您还需要更改您的帮助和错误文本 - 实际上您接受的字符是您说接受的字符。最后,添加一个max_length字段以匹配您现有的帮助文本。

class CustomChangeForm(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 "
                         "@.+-_/\ characters.")}),
        max_length=30)
        ....

编辑

要覆盖 UserChangeForm 重写类语句,以便您的表单继承自 UserChangeForm 而不是 ModelForm -

from django.contrib.auth.forms import UserChangeForm

class CustomChangeForm(UserChangeForm):
    username = forms.RexField(
        ...

查看文档以获取有关Django 表单继承的更多信息。

于 2012-11-26T07:41:34.100 回答