After looking at django's code it does not look like you can just add
a clean_<field_name> method to your model like you can do with forms.
I guess a 'clean' method is the way to go here. But try to raise the
ValidationError with a error dictionary like:

ValidationError({'<field_name>': '<error_msg>'})

So in your case that would be:

def clean(self):
    if self.is_video and not self.aspect_ratio:
        raise ValidationError({'aspect_ratio': 'The aspect ratio is
required for video titles.'})

I never tried this myself and I just made this up after a short glance
on the django code base so I am not sure if this works.
But a small tip: There is not much magic involved with django's code
base and after all django is just python. You can solve a lot of
questions by looking at django's well organized code. In this case
have a look at django/db/models/base.by line 808 and 841 (current
trunk) at the methods full_clean and clean_fields.

On Mar 11, 6:56 am, Julien Phalip <[email protected]> wrote:
> Hi,
>
> It's the first time I'm playing with model validation, and I'm a bit
> stuck with something. I couldn't find any help on this mailinglist or
> in the doc, but if there is please let me know where :)
>
> Basically I'd like to validate a model field in the context of its
> instance. First I assumed it would work like with form validation, so
> I did:
>
> class Title(models.Model):
>     is_video = models.BooleanField(...)
>     aspect_ratio = models.CharField(...)
>     ...
>
>     clean_aspect_ratio(self, value):
>         if self.is_video is True and value == '':
>             raise ValidationError('The aspect ratio is required for
> video titles.')
>
> But this doesn't work. The 'clean_aspect_ratio' method is never
> called. I could use validators, but from there I can't have access to
> the model instance and therefore I can't access the 'is_video'
> attribute. It sort of works with the 'clean' method:
>
> class Title(models.Model):
>     ...
>
>     clean(self):
>         if self.is_video and value == '':
>             raise ValidationError('The aspect ratio is required for
> video titles.')
>
> However, this error is not attached specifically to the 'aspect_ratio'
> attribute, therefore the error is displayed at the top of the admin
> form rather than next to the aspect_ratio form field.
>
> Is there a way to achieve the same type of specific validation like
> with forms?
>
> Many thanks,
>
> Julien

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to