Reputation: 41
I've got some problems with Django DateTimeField. I want my script to add 7 days to expiration_date field in database when some conditions occur.
models.py
class TrainingPlan(models.Model):
user = models.OneToOneField(User, on_delete='CASCADE')
exercise_list = models.ManyToManyField(Exercise)
expiration_date = models.DateTimeField(default=datetime.now(timezone.utc))
reps = models.PositiveIntegerField(default=10)
views.py
def check_plan_expiration_date():
user_exp_date = user_trainingplan.expiration_date
now = datetime.now(timezone.utc)
if user_exp_date <= now:
user_exp_date = datetime.now(timezone.utc)+timedelta(days=7)
user_exp_date.save()
else:
return user_exp_date
Error I get: 'datetime.datetime' object has no attribute 'save'
Upvotes: 1
Views: 2339
Reputation: 2784
You're calling the save()
method on the wrong object / variable. You want to set the new user_exp_date
to the user_trainingplan.expiration_date
attribute and call user_trainingplan.save()
def check_plan_expiration_date():
user_exp_date = user_trainingplan.expiration_date
now = datetime.now(timezone.utc)
if user_exp_date <= now:
user_trainingplan.expiration_date = datetime.now(timezone.utc)+timedelta(days=7)
user_trainingplan.save()
else:
return user_exp_date
Upvotes: 1
Reputation: 5793
Work with the model
def check_plan_expiration_date():
now = datetime.now(timezone.utc)
if user_trainingplan.expiration_date <= now:
user_trainingplan.expiration_date = datetime.now(timezone.utc)+timedelta(days=7)
user_trainingplan.save()
else:
return user_trainingplan.expiration_date
Upvotes: 1