如何在Django用户名正则表达式中允许空格? [英] How can I allow spaces in a Django username regex?

查看:187
本文介绍了如何在Django用户名正则表达式中允许空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图允许空格被接受到缺省django.contrib.auth.models用户名的用户名字段中,其他人之前已直接或类似的问题询问:这里这里这里。我试图实现这些建议,但是我似乎找不到一个很好的例子来说明如何使它工作。

I am trying to allow spaces to be accepted into the username field of the default django.contrib.auth.models User, other people have asked directly or similar questions before: Here, Here, and Here. I have tried to implement these suggestions however I cannot seem to find a good example of how to get this to work.

根据我的理解,我需要更改用户名字段验证器中的正则表达式,为此我可以从contrib.auth.forms覆盖UserCreationForm来实现其他字段用于用户名,并提供我自己的验证。 (如答案中所建议的)。

From what I understand I need to change the regex in the username field validator, to do this I can override the UserCreationForm from contrib.auth.forms to implement a different field for username and provide my own validation. (as suggested in this answer).

我如何具体做?

供参考,这是我正在用作注册形式:

for reference, this is currently what I am using as a signup form:

class SignUpForm(forms.ModelForm):
    """
    This form class is for creating a player
    """
    username = forms.CharField(label='Gamertag', max_length=16, widget=forms.TextInput(attrs={'placeholder': 'Gamertag', 'class': 'form-input'}))
    email = forms.EmailField(label='email', widget=forms.TextInput(attrs={'placeholder': 'Email', 'class': 'form-input', 'type':'email'}))
    password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'form-input'}))

    class Meta:
        model = User
        fields = ['username',
                  'email',
                  'password']
        widgets = {
            'password': forms.PasswordInput(),
        }

    def clean_email(self):
        email = self.cleaned_data.get('email')
        username = self.cleaned_data.get('username')
        if email and User.objects.filter(email=email).exclude(username=username).count():
            raise forms.ValidationError(u'A user with that email already exists.')
        return email


推荐答案

如果你是不要尝试修改默认User类的字段,另一个Jonathan对于1.10的回答是很好的,除了一个小错误( username_validator = MyValidator 需要 username_validator = MyValidator()所有字符是允许的)。最终的代码如下:

If you aren't trying to modify the fields on the default User class, the other Jonathan's answer for post 1.10 is good except for a small mistake (username_validator = MyValidator needs to be username_validator = MyValidator() or all characters are allowed). The final code looks like:

from django.contrib.auth.models import User
from django.contrib.auth.validators import UnicodeUsernameValidator

class MyValidator(UnicodeUsernameValidator):
    regex = r'^[\w.@+-\s]+$'

class MyUser(User):
    username_validator = MyValidator()

    class Meta:
        proxy = True  # If no new field is added.

(只需将 UnicodeUsernameValidator 替换为 ASCIIUsernameValidator 如果使用Python 2)

(simply replace UnicodeUsernameValidator with ASCIIUsernameValidator if using Python 2)

如果要修改User类的字段,则可能是 AbstractUser ,您不能使用 proxy = True 。这意味着 AbstractUser 上的用户名字段将使用 username_validator AbstractUser 上声明,而不是您的。要解决这个问题,您几乎必须在模型上重新声明 username ,如下所示:

If you are modifying the fields on your User class, you are probably subclassing AbstractUser and you can't use proxy = True. This means the username field on AbstractUser will use the username_validator declared on AbstractUser, not yours. To fix this, you pretty much have to re-declare username on your model, like so:

from django.contrib.auth.models import AbstractUser
from django.contrib.auth.validators import UnicodeUsernameValidator
from django.utils.translation import ugettext_lazy as _    

class MyValidator(UnicodeUsernameValidator):
    regex = r'^[\w.@+-\s]+$'

class MyUser(AbstractUser):
    username_validator = MyValidator()
    username = models.CharField(
        _('username'),
        max_length=150,
        unique=True,
        help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
        validators=[username_validator],
            error_messages={
            'unique': _("A user with that username already exists."),
        },
    )

确保运行makemigrations并在warww之后迁移ds。

Make sure you run makemigrations and migrate afterwards.

我已经尝试了一些方法,在用户名已经被声明之后更改验证器,但没有运气,所以看起来像这是现在最好的方式。

I've tried a number of ways to change the validators on username after it has already been declared, but haven't had any luck, so it looks like this is the best way for now.

这篇关于如何在Django用户名正则表达式中允许空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆