i'm trying implement generic views in django 1.8 app, django can take care of validation/redirection loop me.
i've created model:
class customer(models.model): custid = models.charfield(max_length=4, verbose_name='cid (4 alphanumeric uppercase)', validators=[validators.cidvalidator]) customer_shortcode = models.charfield(max_length=7, verbose_name='customer code (7 chars, uppercase, no spaces)', validators=[validators.shortnamevalidator]) description = models.charfield(max_length=30, blank=true)
and defined validator each of 2 validated fields:
class cidvalidator(regexvalidator): regex = r'^[a-z0-9]{4}$' message = 'cid 4-character uppercase alphanumeric value' class shortnamevalidator(regexvalidator): regex = r'^[a-z0-9_]{1,7}$' message = 'shortname should uppercase, no spaces, alphanumeric'
(at point, expected admin interface use validators when added customer, doesn't)
for actual app, i've created modelform customer class:
class customerform(modelform): class meta: model = customer fields = ['custid', 'customer_shortcode', 'description']
and view class inherited createview:
class customercreateview(createview): model = customer form_class = customerform def get_success_url(self): return reverse('customer_list')
and still don't validation errors when enter invalid data in generated form.
as far can follow docs, should need override clean() or clean_xxx() on modelform additional validation, not this, it's unclear. i'd keep knowledge constitutes valid value in few places possible - validator on modelfield do.
what missing here? suspect i'm getting confused between model validation , form validation...
tl;dr: when specifying kind of validators in model field definitions, should pass instances rather classes (validators.cidvalidator()
instead of validators.cidvalidator
).
longer explanation
django validators need callables. trying call class passing go through python's creation sequence instance, calling __new__
, __init__
, , return instance of class - won't in terms of validating field value.
the django validators subclassing have __call__
method, run when try call instance of class, , takes care of validating , raising validationerror
s
Comments
Post a Comment