103👍
You would use a validator to limit what the field accepts. A RegexValidator
would do the trick here:
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_email
validator that’ll validate email addresses for you; the alphanumeric
validator above will not allow for valid email addresses.
2👍
Instead of RegexValidator, give validation in forms attributes only like…
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
- [Django]-No module named django but it is installed
- [Django]-When to use Serializer's create() and ModelViewset's perform_create()
- [Django]-How to make python on Heroku https only?
2👍
That is little bit wider than you want, but you also can use SlugField
:
A Slug is basically a short label for something, containing only
letters, numbers, underscores or hyphens. They’re generally used in
URLs. For example, in a typical blog entry URL:
https://www.geeksforgeeks.org/add-the-slug-field-inside-django-model/
field_name = models.SlugField(max_length=200, **options)
- [Django]-Django model with 2 foreign keys from the same table
- [Django]-Install mysql-python (Windows)
- [Django]-Django REST Framework – Serializing optional fields
0👍
email validation using django form
with danish special characters also
import re
email_regex = r'\b[A-Za-z0-9._%+-øØæÆåÅ]+@[A-Za-z0-9.-øØæÆåÅ]+\.[A-Z|a-z]{2,}\b'
if email and not re.search(email_regex, email):
raise forms.ValidationError({"email": "Enter a valid email"})
- [Django]-How to go from django image field to PIL image and back?
- [Django]-Mysql error : ERROR 1018 (HY000): Can't read dir of '.' (errno: 13)
- [Django]-Django Broken pipe in Debug mode
0👍
You can make use of builtin string isalnum function to check whether input is alphanumeric or not.
def alphanumeric(value):
if not str(value).isalnum():
raise ValueError("Name can have number or character no special characters")
name = models.CharField(max_length=100, blank=True, null=True, validators=[alphanumeric])
- [Django]-Apache or Nginx to serve Django applications?
- [Django]-How do I restrict foreign keys choices to related objects only in django
- [Django]-Django Rest Framework: Access item detail by slug instead of ID