views:

188

answers:

2

Let's say that I have a model:

class Ticket(models.Model):
    client = models.ForeignKey(Client)
    color = models.CharField(max_length=255)

    def clean(self):
        self.color = self.client.favorite_color

When I run this on the latest Django (head of the SVN from 15 minutes ago), if I hit save without selecting a client, I get a DoesNotExist error from inside my clean method (for the self.client.favorite_color part). Since the model requires the client attribute, shouldn't this be handled before my custom validation in clean()?

Here's the documentation I'm reading: http://docs.djangoproject.com/en/dev/ref/models/instances/#id1

A: 

clean() is a callable of ModelForms, not models.

See the docs.

To do what you seem to want to do at the Model level, override the save() method.

Edit after comment: Well, it appears it is time to read the docs all over again with 1.2 impending. :-) Thanks for pointing it out.

celopes
clean() is a model method now too. Here's a link: http://docs.djangoproject.com/en/dev/ref/models/instances/#id1
orokusaki
@celopes LOL, I know. I would complain but I'm early enough into my project that I'm pulling weekly SVN down and working out bugs as I go because this model validation is something I've always dreamed of and there's more new stuff like queryset.exists(), etc. If you're going to use SVN for this new validation, I'd grab revision #12268.
orokusaki
A: 

I figured it out if anyone runs into this problem:

In full_clean() on the model, first clean_fields() is run, but no errors are raised for display, etc. Instead they are simply added to a dict() and then clean(), which is the custom validation method for your model is run to add any of your custom errors to the dict. Only after that are the errors raised again.

orokusaki