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=True, blank=False)
Date = models.DateField(null=True, blank=False)
Month = models.CharField(max_length=100, null=True, blank=False)
def get_month(self):
if self.Date:
self.Month = self.Date.strftime("%B")
self.save()
I saw this question on SO and tried it out, but nothing seems to be happening. What am I missing? Do I have to create one of these? Thanks.
You can simply override your
save
to add the auto-field instead of callingsave
in a new method: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:You can use the property like so: