Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django alphanumeric CharField

How can I create a CharField on a Django model that can only have numbers and letters?

models.CharField(_('name'), max_length=50, null=False, blank=False)
like image 291
JMira Avatar asked Dec 07 '22 22:12

JMira


2 Answers

another option is to use validators option for the CharField (docs)

like image 87
Jerzyk Avatar answered Dec 09 '22 15:12

Jerzyk


Control at Model-level may include some unwanted behavior, these are equivalent to schema constraints and will apply when manipulating the db (ie: backups), if you are absolutely sure you need control at Model level instead of Form then you should define a new validator or use an existing one.

The basic way of testing a string for alphanumeric is

'string'.isalpha()

You could put that evaluation in the save method of the model, but if you want to have more control or raise a ValidationError automatically you can define a validator for the model. This way let's you do unit testing without involving the form. However, make sure your implementation doesn't affect your performance.

Example:

"automated tasks fetching hex32 tokens from a remote server", so you check those tokens at run time with a validator like:

RegexValidator(r'^[A-Fa-f0-9]{32}$',
               message='Key must be Hex len 32',
               code='Invalid Key')

And if it doesn't match you raise a ValidationError with the details automatically.

In your case, you could do:

models.py:

from validators import isalphavalidator

class SomeModel(Model):
    some_alpha_field = models.CharField(_('name'), validators=[isalphavalidator], max_length=50, null=False, blank=False)

validators.py

from django.core.validators import RegexValidator


'''
This regex assumes that you have a clean string,
you should clean the string for spaces and other characters
'''

isalphavalidator = RegexValidator(r'^[\w]*$',
                             message='name must be alphanumeric',
                             code='Invalid name')
like image 20
cpersico Avatar answered Dec 09 '22 16:12

cpersico