简体   繁体   中英

Validator on a Django form field gives Attribute Error

I made a validator for a field on a Django form I made. Here is the validator:

from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy

def validate_value(value):
    if value.isalpha():
        if len(value) != 1:
            raise ValidationError(
                ugettext_lazy('Invalid zone value: %(value)s'),
                params={'value': value}
            )
    elif value.isdecimal():
        if int(value) == 0:
            raise ValidationError(
                ugettext_lazy('Invalid zone value: %(value)s'),
                params={'value': value}
            )
    else:
        raise ValidationError(
            ugettext_lazy('Invalid zone value: %(value)s'),
            params={'value': value}
        )

What this validator does is take in a string and see if it's either a single letter or a number. If it's none of those or that number equals zero, then it raises the validation error. For example, "a" and "3" will be accepted, but "a1" will raise the error. Below is the form that the validator is attached to:

from django import forms
from values.validators import validate_value

class LetterOrNumberForm(forms.Form):
    value = forms.CharField(validators=[validate_value])

The problem comes when I test the form. What the form should do when a bad input is entered is show the validation error above the field. When I put in a value that is supposed to pass, like "a" or "3", the form works fine. But when I put in a bad input such as "a1", Django crashes and I get this error:

'NoneType' object has no attribute 'isdecimal'

The template and view is pretty standard for Django forms so I doubt the problem is there, and if I take that validator and configure it to be in the clean function of the form, it actually works. However, I want to use the validator. Does anyone know what could be causing the problem? Thanks.

I solved it. Turns out that it was something else in the form code that was causing the problem, not the validator itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM