【问题标题】:How can I allow spaces in a Django username?如何在 Django 用户名中允许空格?
【发布时间】:2013-11-11 16:23:12
【问题描述】:

我正在尝试在我的 Django 应用程序中允许用户名中有空格。这是我的表格:

class SignUpForm(django.forms.ModelForm):
...
    username = django.forms.RegexField(
       regex=r'^[a-zA-Z]{1}[a-zA-Z -]{1,29}$'

我希望用户名以字母开头。之后,我允许使用字母、空格和连字符。不知何故,表单无法通过“John Smith”验证,我不知道为什么。其他地方有空间限制吗?

【问题讨论】:

  • 您可以尝试改用setattr方法
  • 你试过转义正则表达式中的空间吗?即:'\'

标签: python django


【解决方案1】:

django auth 用户基于一个抽象用户类 (django.contrib.auth.models)。您的绑定表单可能有效,但如果您尝试保存用户对象验证失败。

查看来自 django.contrib.auth.models 的关于用户名的来源:

class AbstractUser(AbstractBaseUser, PermissionsMixin):
    """
An abstract base class implementing a fully featured User model with
admin-compliant permissions.

Username, password and email are required. Other fields are optional.
"""
    username = models.CharField(_('username'), max_length=30, unique=True,
        help_text=_('Required. 30 characters or fewer. Letters, digits and '
                    '@/./+/-/_ only.'),
        validators=[
            validators.RegexValidator(r'^[\w.@+-]+$', _('Enter a valid username.'), 'invalid')
        ])

希望这能对它有所启发。

【讨论】:

    猜你喜欢
    • 2018-11-19
    • 2017-02-10
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 2017-01-28
    • 1970-01-01
    • 1970-01-01
    • 2016-10-14
    相关资源
    最近更新 更多