希望你们的人帮助我Config RegexField只接受连字符( - )和数字只在Django Rest Framework中
现在我配置:
username = RegexField(regex=r'^[\d-]+$', required=True, max_length=50)
我的序列化器:
class UserSignUpSerializer(ModelSerializer):
username = RegexField(regex=r'^[\d-]+$', required=True, max_length=50)
email = EmailField(required=True, allow_blank=False, max_length=50)
password = CharField(required=True, allow_blank=False, max_length=20)
class Meta:
model = User
fields = [
'username',
'email',
'password'
]
extra_kwargs = {"password": {"write_only": True}}
它不起作用!
提前致谢!
答案 0 :(得分:1)
该正则表达式允许使用任何字母数字字符(a to z
,A to Z
和0 to 9
)。
您正在寻找:
# \d allows only numeric digits
# - or \- allows only hyphen
# [\d-] allows a single character, either a digit or a hyphen
# [\d-]+ allows for more than one character, but a minimum of one is required
# ^[\d-]+$ the whole input string must match the regular expression
RegexField(regex=r'^[\d-]+$', required=True, max_length=50)