Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to add 2 days to an existing date entered by user

I am trying to add a a payment due date 2 days after the event

class Payment(models.Model):       
    event_date = models.DateField()        
    payment_due_date = models.DateField()    


    class Meta:
        ordering = ["payment_due_date"]

    def payment_due_date(self):
         event_date = self.event_date
         return event_date + datetime.timedelta(days=2)

Pycharm gives me a error highligting Expected type 'timedelta', got 'DateField' instead more... (Ctrl+F1)

how can I fix this issue

Error in Terminal

match = date_re.match(value) TypeError: expected string or bytes-like object

like image 380
Samir Tendulkar Avatar asked Feb 12 '19 19:02

Samir Tendulkar


People also ask

How do I change the date automatically changes in a value in Django?

You want to add the auto_now field and set it to True. This will update with the current timestamp each time you update the model.

What is timestamped model in Django?

TimeStampedModel - An Abstract Base Class model that provides self-managed created and modified fields.


1 Answers

You could override your save() method in your model.

Note that a DateTimeField in Django becomes a datetime.datetime object. So to retrieve the date from it, you need to call field.date().

Example:

models.py

from django.db import models
import datetime

class Payment(models.Model):
    event_date = models.DateField()
    payment_due_date = models.DateField()

    class Meta:
        ordering = ["payment_due_date"]

    def save(self, *args, **kwargs):
        if self.payment_due_date is None:
            self.payment_due_date = self.event_date.date() + datetime.timedelta(days=2)
        super(Payment, self).save(*args, **kwargs)
like image 121
JoshG Avatar answered Oct 06 '22 05:10

JoshG