2012-12-16 30 views
5

因爲問這個問題我覺得很愚蠢,但我仍然會這麼做。 Django文檔"User authentication in Django"(1.4版)中的用戶API參考指出,用戶名只能包含字母,數字和字符@,+,。, - 和_。然而,我可以進入Python的外殼並執行以下操作:爲什麼models.User在用戶名中允許使用無效字符?

>>> from django.contrib.auth.models import User 
>>> u = User.objects.create_user('joe#') 

爲什麼沒有這引發異常?我查看了../contrib/auth/models.py中的源代碼,它似乎沒有標記無效字符。這裏發生了什麼?看起來,如果你想捕捉錯誤的用戶名,你必須通過表單驗證來完成。

回答

4

我猜想開發人員希望爲應用程序開發人員提供靈活性,以便我們可以存儲特殊符號。因此,不是在模型層面驗證輸入,而是在表單中完成輸入。你可以發現裏面django.contrib.auth.form.UserCreationForm

形式的片段是在這裏:

可以使用在用戶名字段的正則表達式見驗證。

class UserCreationForm(forms.ModelForm): 
    """ 
    A form that creates a user, with no privileges, from the given username and 
    password. 
    """ 
    error_messages = { 
     'duplicate_username': _("A user with that username already exists."), 
     'password_mismatch': _("The two password fields didn't match."), 
    } 
    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.")}) 
    password1 = forms.CharField(label=_("Password"), 
     widget=forms.PasswordInput) 
    password2 = forms.CharField(label=_("Password confirmation"), 
     widget=forms.PasswordInput, 
     help_text = _("Enter the same password as above, for verification.")) 
+0

我明白了。非常感謝,Raunak! – William

+0

您的代碼中的正則表達式是否包含下劃線字符? – Fydo

+0

不要認爲這是一個好主意,因爲它會造成不一致。看[這個問題](https://github.com/pennersr/django-allauth/issues/1321) –

相關問題