Skip to main content
 首页 » 编程设计

python之如何在 Django 用户名中允许空格

2024年08月28日30youxin

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

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

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

请您参考如下方法:

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

查看 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') 
        ]) 

希望这对它有所启发。