Home > Mobile >  Boolean field update due to another field change in Django Admin
Boolean field update due to another field change in Django Admin

Time:02-01

I have model Department like:

class Department(models.Model):
    dep_title = models.CharField(max_length=30, verbose_name='Title')
    dep_description = models.CharField(max_length=100, blank=True, verbose_name='Description')
    dep_status = models.BooleanField(default=False, verbose_name='Is Active?')
    dep_start = models.DateField(verbose_name='Date of Establishment')
    dep_end = models.DateField(blank=True, verbose_name='Closing Date', null=True)

and DepartmentAdmin:

class DepartmentAdmin(admin.ModelAdmin):
    list_display= ('dep_title','dep_description','dep_status', 'dep_start', 'dep_end')

I want to check dep_end date and if date is expired, set automatically dep_status = False

How can I implement this?

CodePudding user response:

You can to override your save function. Like this:

class Department(models.Model):
    dep_title = models.CharField(max_length=30, verbose_name='Title')
    dep_description = models.CharField(max_length=100, blank=True, verbose_name='Description')
    dep_status = models.BooleanField(default=False, verbose_name='Is Active?')
    dep_start = models.DateField(verbose_name='Date of Establishment')
    dep_end = models.DateField(blank=True, verbose_name='Closing Date', null=True)
    def save(self, *args, **kwargs):
        if self.dep_end > ## Expiration date here ##:
            self.dep_status = False
        super(Department, self).save(*args, **kwargs)

Now every time your model saves, it will check to see if the dep_end date is past your expiration date.

  •  Tags:  
  • Related