Populate Month Based On Date Field In Django
I would like to have a field auto-generate the month based on the date entered before it. models.py class Projects(models.Model): Name = models.CharField(max_length=100, null=
Solution 1:
You can simply override your save
to add the auto-field instead of calling save
in a new method:
classProjects(models.Model):
Name = models.CharField(max_length=100, null=True, blank=False)
Date = models.DateField(null=True, blank=False)
Month = models.CharField(max_length=100, null=True, blank=False)
defsave(self, *args, **kwargs):
if self.Date:
self.Month = self.Date.strftime("%B")
super(Model, self).save(*args, **kwargs)
But the above will make Month
available only after the instance has been saved.
You can instead create a property, so that Month
is available from an instance of the model and also prevent adding duplicate info in your DB:
classProjects(models.Model):
Name = models.CharField(max_length=100, null=True, blank=False)
Date = models.DateField(null=True, blank=False)
@propertydefMonth(self):
if self.Date:
return self.Date.strftime("%B")
return"No date entry"
You can use the property like so:
import datetime.date as dt
# import your Projects model
p = Projects(Name='ceuskervin', Date= dt.today())
print(p.Month)
Post a Comment for "Populate Month Based On Date Field In Django"