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?
有什么办法吗?
2 个解决方案
#1
44
You would use a validator to limit what the field accepts. A RegexValidator
would do the trick here:
您将使用验证器来限制字段接受的内容。一个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_email
validator that'll validate email addresses for you; the alphanumeric
validator above will not allow for valid email addresses.
请注意,已经有一个validate_email验证程序可以为您验证电子邮件地址;上面的字母数字验证器不允许有效的电子邮件地址。
#2
1
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
否则,您将不得不处理视图中的错误。它适用于我尝试这个简单的方法...这将允许用户只输入字母和空格
#1
44
You would use a validator to limit what the field accepts. A RegexValidator
would do the trick here:
您将使用验证器来限制字段接受的内容。一个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_email
validator that'll validate email addresses for you; the alphanumeric
validator above will not allow for valid email addresses.
请注意,已经有一个validate_email验证程序可以为您验证电子邮件地址;上面的字母数字验证器不允许有效的电子邮件地址。
#2
1
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
否则,您将不得不处理视图中的错误。它适用于我尝试这个简单的方法...这将允许用户只输入字母和空格