[Answered ]-How do I calculate the date : one year from the creation with a DateTimeField?

1πŸ‘

βœ…

See https://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods:

updated

because you cannot use self.created in the setting of expired.

models.py

class Subscription(models.Model):
    user = models.ForeignKey(User)
    subscribed = models.BooleanField(default=False)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    expired = models.DateTimeField()

    def save(self, *args, **kwargs):
        self.expired = datetime.datetime.now()+datetime.timedelta(365) # original answer used this line: self.created + datetime.timedelta(365).isoformat()
        super(Subscription, self).save(*args, **kwargs) # Call the "real" save() method.

1πŸ‘

Your date calculation is calling isoformat on the timedelta instance you are creating, which I suspect is where your error is coming from.

I think you just need some parentheses (and self):

date = (self.created + datetime.timedelta(365)).isoformat()
πŸ‘€Blckknght

0πŸ‘

Assuming you’re going to stick with expired being a DateTimeField on the model, then what you really want to do is override clean

def clean(self):
    if self.expired is None:
        self.expired = self.created + timedelta(days=365)
    return super(Subscription, self).clean()
πŸ‘€Chris Pratt

Leave a comment