开发者

Django alphanumeric CharField

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

models.CharField(_('name'开发者_如何学JAVA), 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.

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')


Don't use a CharField use a RegexField instead with regex="[A-z0-9]+"

You can make the field real easy using the same logic:

class AlphaNumericField(CharField):
    def clean(self, value, model_instance):
        value = super(AlphaNumericField, self).clean(value, model_instance)
        if not re.match(r'[A-z0-9]+', value):
            raise ValidationError('AlphaNumeric characters only.')
        return value


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...

If you are using RegexValidator 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜