如何覆盖UserChangeForm

时间:2012-11-26 06:56:07

标签: python regex django django-forms

这是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

非常感谢

1 个答案:

答案 0 :(得分:0)

你的正则表达式没有做你想要的。找一些关于正则表达式的教程(google'正则表达式教程')。然后我建议使用一些软件来测试正则表达式(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(
        ...

有关inheritance with Django forms的更多信息,请查看文档。