2012-11-26 177 views
1

Thie是Django中的源代碼,當更改名爲「xxx /// \」的用戶的權限時,它將會出現錯誤,但事實上我不想阻止這種格式用戶名,所以我想覆蓋UserChangeForm類。你能告訴我如何做到這一點?謝謝!如何覆蓋UserChangeForm

class UserChangeForm(forms.ModelForm): 
    username = 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.")}) 
    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"^[[email protected]\.+-_\/\\]+$", 
     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 

感謝所有同

回答

0

你的正則表達式是不是做你想要什麼。找到正則表達式的一些教程(谷歌'正則表達式教程')。然後,我建議獲得一些軟件來測試正則表達式(Windows上的Regex Coach很棒)。

我覺得表達式^[[email protected]\.+-_\/\\]+$。應該做你想要的。您還需要更改您的幫助和錯誤文本 - 實際上您接受的其他字符是您所接受的字符。最後,添加一個max_length字段以匹配您現有的幫助文本。

class CustomChangeForm(forms.ModelForm): 
    username = 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.")}), 
     max_length=30) 
     .... 

編輯

要覆蓋UserChangeForm重寫類語句,這樣您的形式從UserChangeForm而不是繼承的ModelForm -

from django.contrib.auth.forms import UserChangeForm 

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

看一看在文檔上inheritance with Django forms更多信息。

+0

感謝您的回覆,是的,正則表達式被破壞,因爲我粘貼的代碼是Django的源代碼,而不是我自己。我可以在Django代碼中修改正則表達式,但是我想在自己的xx.py文件中覆蓋它。 – jimwan

+0

我已經更新了我的答案 –