Home > OS >  can't edit Boolean field on django model when it is link with another field from the same model
can't edit Boolean field on django model when it is link with another field from the same model

Time:05-30

I am working on django v4.* and I came cross a point where I need to make field publish_date to be auto populated when is_published is ticked

import datetime
class Article(models.Model):
     .......
     is_published = models.BooleanField(default=False)
     publish_date = models.DateTimeField(blank=True, null=True)
     .......
     def save(self, *args, **kwargs):
        if self.is_published:
           self.publish_date = datetime.datetime.now()
           super().save(*args, **kwargs)

this did the trick but the problem that I can not edit the is_published field anymore, when I tick it (make it true) it stay true even if I try to change it to untick

CodePudding user response:

Your save action is now part of your if: statement. Drop it down an indent level so that it always ends the function

 def save(self, *args, **kwargs):
    if self.is_published:
       self.publish_date = datetime.datetime.now()
    super().save(*args, **kwargs)
  • Related