clean method in a model

85 views
Skip to first unread message

refreegrata

unread,
Nov 8, 2010, 3:40:41 PM11/8/10
to Django users
Hello list. I want to use the clean method in a model.
--------------------------------------
class myModel(models.Model):
fields ....

def clean(self):
raise ValidationError('The Error.')
-------------------------------------------------------

Thats works fine. My question is, how can I associate this error to
the field in the modelform?. With this method the form validation can
be controlled, but I can't pick the error dynamically to show at the
user.

Thanks for read.

cootetom

unread,
Nov 8, 2010, 5:17:32 PM11/8/10
to Django users
If you want to associate an error to a specific field in a model form
then you need to populate self._errors with the error you find. Have a
read about this on the Django docs to see how it is done.

http://docs.djangoproject.com/en/1.1/ref/forms/validation/#ref-forms-validation

The last example shows how to associate a error with a specific field
in a form class.

refreegrata

unread,
Nov 9, 2010, 9:39:36 AM11/9/10
to Django users
ok, thanks for the answer, but I want use the clean method in a model,
not in a form. For that in the clean method I throw a ValidationError,
but the error message isn't associated to the field form of the
modelform.

On 8 nov, 19:17, cootetom <coote...@gmail.com> wrote:
> If you want to associate an error to a specific field in a model form
> then you need to populate self._errors with the error you find. Have a
> read about this on the Django docs to see how it is done.
>
> http://docs.djangoproject.com/en/1.1/ref/forms/validation/#ref-forms-...

cootetom

unread,
Nov 9, 2010, 11:44:24 AM11/9/10
to Django users
You say you want to do the clean in the model but then say you want
the error to be associated with the field in the ModelForm? If you
need that clean functionality to exist for both a model and a form of
that model then you could shift the checks into a function of it's own
out side of the class's then have a clean in both the model and the
form which calls the function to do the checks before deciding how to
raise the error.

The issue is that a form and a model use validation errors in
different ways. A form will send errors back to the templating layer
to show to a user but a model doesn't work like that as it would only
be manipulated directly in python code.

Does that make sense?

refreegrata

unread,
Nov 9, 2010, 3:25:40 PM11/9/10
to Django users
Thanks for answer. You have reason, I don't need do that. With a clean
method in the modelform is enough. This question appear, because
initialy I just wanted add a validator to the field of the model, but
for the validation the parameter "self" was necessary and I could
not find a way to pass this parameter. However I don't need this, with
a clean method in the form, I can solve this quickly.
Reply all
Reply to author
Forward
0 new messages