开发者

Django: Does model_instance.clean() run before basic validators?

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 rea开发者_运维百科ding: http://docs.djangoproject.com/en/dev/ref/models/instances/#id1


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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜