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?
django-forms Using Model Form Making fields not editable Django 1.9 added the Field. disabled attribute: The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won't be editable by users.
The simplest way is by using the field option blank=True (docs.djangoproject.com/en/dev/ref/models/fields/#blank).
CharField() is a Django form field that takes in a text input.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With