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)
another option is to use validators
option for the CharField (docs)
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.
"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')
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