Regexfield不足以验证文本输入(Django表单)

时间:2017-02-02 11:39:42

标签: regex django unicode django-forms

在Django表单中,用户设置其用户名。表单中的用户名字段定义如下:

    username = forms.RegexField(max_length=50,regex=r'^[\w.@ +-]+$',
            help_text=_("Required. 50 characters or fewer. Letters, digits and "
                          "@/./+/-/_ only."),
            error_messages={
                'invalid': _("This value may contain only letters, numbers and "
                             "@/./+/-/_ characters.")})

匹配正则表达式时进行验证,否则不进行验证。例如,设置用户名Bender*无效,Bender@有效。

我注意到如果用户输入阿拉伯语或波斯语文本而不是优雅地使其无效,我的表单会抛出一个令人讨厌的错误。例如。如果尝试العربی作为用户名,则抛出以下内容:

UnicodeEncodeError at /keep_username/

'ascii' codec can't encode characters in position 0-5: ordinal not in range(128) 

为什么这段文字没有像往常一样无效(我该怎么做才能解决这个问题)?

提前致谢!

2 个答案:

答案 0 :(得分:2)

RegexField可以采用编译的正则表达式和字符串。我们应该这样试试吗?

import re

regex = re.compile('^[\w.@ +-]+$',re.UNICODE)

class Myclass(models.Model):

     username = forms.RegexField(max_length=50,regex=regex,
            help_text=_("Required. 50 characters or fewer. Letters, digits and "
                          "@/./+/-/_ only."),

答案 1 :(得分:1)

您也可以使用RegexValidator

处理它

代表forms.py

from django import forms
from django.core.validators import RegexValidator


class FooBar(forms.Form):
    username_validator = RegexValidator(r'^[\w.@ +-]+$', 
                                        "This value may contain only letters, "
                                        "numbers and @/./+/-/_ characters
    username = forms.CharField(validators=[username_validator])

或在models.py

from django.db import models
from django.core.validators import RegexValidator


class FooBar(models.Model):
    username_validator = RegexValidator(r'^[\w.@ +-]+$', 
                                        "This value may contain only letters, "
                                        "numbers and @/./+/-/_ characters
    username = models.CharField(max_length=200, validators=[username_validator])