Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a Django form field contain only alphanumeric characters

Tags:

python

django

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?

like image 778
user1958218 Avatar asked Jun 18 '13 09:06

user1958218


People also ask

How do you make a field non editable in Django?

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.

How do you make a field non mandatory in Django?

The simplest way is by using the field option blank=True (docs.djangoproject.com/en/dev/ref/models/fields/#blank).

Is a Django form field that takes in a text input?

CharField() is a Django form field that takes in a text input.


2 Answers

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.

like image 81
Martijn Pieters Avatar answered Oct 21 '22 02:10

Martijn Pieters


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

like image 23
Javed Avatar answered Oct 21 '22 01:10

Javed