开发者

Model validation. Don't want to repeat myself. Django

I have a model M that has a field num=models.IntegerField()

I have a modelform called F for model M.

I want to ensure that num is never negative.

If I do validation in my form class, F, then I can do clean_num(): if negative then throw ValidationError('Num can never be negative'). This ValidationError will be automatically redisplayed to the user by redirecting him to back to the form that he submitted and displaying the 'Num can never be negative' message on top of the num field. Thats all done automatically by django as soon as I throw the ValidationError from the clean_fieldname method.

I wou开发者_运维知识库ld like to be able to do all that, but in the model class.

F is the ModelForm created from a model class M. M defines that the field num can never be negative.

When I'm calling is_valid() on a form, I want the functions defined in the model to check for validation for any ModelForm that references this model.

How can I achieve this?


See Model validation (Django 1.2+ only).


You could also use PositiveIntegerField for this particular problem.

If your validation depends only on field value, you can implement your own field type as described here: https://docs.djangoproject.com/en/dev/howto/custom-model-fields/


Thanks to everyone who posted an answer. But i found exactly what i asked about so if you're interested:

You can define the proper validators just once for the model. All the forms using this model will have the ValidationError('cant use this name') be appended to their field_name.errors list.

Note, that they will be added to the field in the form for which the model field validator is running.

Anyway, check this out:

Django: how to cleanup form fields and avoid code duplication

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜