Python 如何使 Django 表单字段仅包含字母数字字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17165147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I make a Django form field contain only alphanumeric characters
提问by user1958218
I have this model
我有这个模型
name = models.CharField(max_length=50, blank=True, null=True)
email = models.EmailField(max_length=50, unique=True)
I want that the user should not be able to use any other characters than alphanumerics in both fields.
我希望用户不能在两个字段中使用字母数字以外的任何其他字符。
Is there any way?
有什么办法吗?
采纳答案by Martijn Pieters
You would use a validatorto limit what the field accepts. A RegexValidatorwould do the trick here:
您将使用验证器来限制该字段接受的内容。ARegexValidator会在这里解决问题:
from django.core.validators import RegexValidator
alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.')
name = models.CharField(max_length=50, blank=True, null=True, validators=[alphanumeric])
email = models.EmailField(max_length=50, unique=True, validators=[alphanumeric])
Note that there already is a validate_emailvalidatorthat'll validate email addresses for you; the alphanumericvalidator above will not allow for valid email addresses.
请注意,已经有一个validate_email验证器可以为您验证电子邮件地址;alphanumeric上面的验证器不允许使用有效的电子邮件地址。
回答by Javed
Instead of RegexValidator, give validation in forms attributes only like...
而不是 RegexValidator,仅在表单属性中进行验证,例如...
class StaffDetailsForm(forms.ModelForm):
first_name = forms.CharField(required=True,widget=forms.TextInput(attrs={'class':'form-control' , 'autocomplete': 'off','pattern':'[A-Za-z ]+', 'title':'Enter Characters Only '}))
and so on...
等等...
Else you will have to handle the error in views. It worked for me try this simple method... This will allow users to enter only Alphabets and Spaces only
否则,您将不得不处理视图中的错误。它对我有用,试试这个简单的方法......这将允许用户只输入字母和空格

