kubeq24
kubeq24

Reputation: 41

django - how to save(update) datetime field to database

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

Answers (2)

Rolando Cruz
Rolando Cruz

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

HenryM
HenryM

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

Related Questions