Bussiere
Bussiere

Reputation: 1152

post save operation if a filed is null or blank in django models?

here is my code :

class Invitation(models.Model):   
    #other fields here
    Code = models.CharField(max_length=128, null=True, blank=True)
    Tags = models.ManyToManyField("CategorieInvitation", null=True, blank=True)
    Tags = models.ManyToManyField("Usage", null=True, blank=True)
    Note = models.CharField(max_length=128, null=True, blank=True)
    Used = models.BooleanField(default=False, blank=True)
    SendTo = models.EmailField(null=True, blank=True)
    # a revoir
    def post_save(self, model_instance, add):
        if self.Code.__len__() == 0 :
            self.Code = generate_invitation(1)[0]
            self.save()

how to replace Code with the result of generate_invitation if Code is blank or null even if created in django-admin interface ?

regards Bussiere

Upvotes: 0

Views: 134

Answers (1)

Botond Béres
Botond Béres

Reputation: 16683

For what you are trying to do it's probably easier and more efficient to override the save method.

class Invitation(models.Model):   
    #other fields here
    code = models.CharField(max_length=128, null=True, blank=True)
    tags = models.ManyToManyField("CategorieInvitation", null=True, blank=True)
    tags2 = models.ManyToManyField("Usage", null=True, blank=True)
    note = models.CharField(max_length=128, null=True, blank=True)
    used = models.BooleanField(default=False, blank=True)
    send_to = models.EmailField(null=True, blank=True)
    # a revoir

    def save(self, *args, **kwargs):
        if not self.code:
            self.code = generate_invitation(1)[0]

        super(Invitation, self).save(*args, **kwargs)

By the way post_save is not something that should be a model instance method. See: https://docs.djangoproject.com/en/1.4/ref/signals/#signals

Upvotes: 2

Related Questions