【问题标题】:Why does models.User allow invalid characters in username?为什么models.User允许用户名中的无效字符?
【发布时间】:2012-12-16 18:53:03
【问题描述】:

我觉得问这个很愚蠢,但我还是会这样做。 Django 文档"User authentication in Django" (v. 1.4) 中的“用户”API 参考说明用户名只能包含字母、数字和字符@、+、.、- 和_。但是我可以进入 Python shell 并执行以下操作:

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

为什么这不会引发异常?我查看了 ../contrib/auth/models.py 中的源代码,它似乎没有标记无效字符。这里发生了什么?看来,如果您想捕获错误的用户名,则必须通过表单验证来完成。

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    我猜开发人员希望为应用程序开发人员提供灵活性,以便我们可以存储特殊符号。因此,不是在模型级别验证输入,而是在表单中完成。您可以在 django.contrib.auth.form.UserCreationForm 中找到表单

    sn-p 在这里:

    您可以在用户名字段上使用正则表达式查看验证。

    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'^[\w.@+-]+$',
            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."))
    

    【讨论】:

    • 我明白了。非常感谢,劳纳克!
    • 代码中的正则表达式是否包含下划线字符?
    • 不要认为这对他们来说是个好主意,因为它会造成不一致。见this issue
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    • 2012-02-02
    相关资源
    最近更新 更多