I am working on a task manager project, user can define the "ending date" of the task, I would like to change the front end code of a task that isn't completed before the "endind_date".I tried playing around in models.py but i get back this error: "can't compare datetime.datetime to datetime.date"
models.py:
class Task(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
title = models.CharField(max_length=200)
description = models.TextField(max_length=200, null=True, blank=True)
complete = models.BooleanField(default=False)
importance = models.ForeignKey(Importance, null=True, blank=False, on_delete=models.CASCADE)
creation_date = models.DateField(default=timezone.now)
ending_date = models.DateField(null=True, blank=False)
def __str__(self):
return self.title
def is_end_date(self):
if datetime.now() > self.ending_date:
if not self.complete:
return True
else:
pass
else:
pass
html(only included related code to the problem):
{% if task.is_end_date %}
#code
{% else %}
#code
CodePudding user response:
You should convert the datetime
object to a date
, by calling .date()
on it:
from django.utils.timezone import now
class Task(models.Model):
# …
def is_end_date(self):
return now().date() > self.ending_date and not self.complete
Note: It is normally better to make use of the
settings.AUTH_USER_MODEL
[Django-doc] to refer to the user model, than to use theUser
model [Django-doc] directly. For more information you can see the referencing theUser
model section of the documentation.
CodePudding user response:
You can use date.today()
or datetime.now().date()
as
Using date.today()
as
from datetime import date
def is_end_date(self):
if date.today() > self.ending_date:
if not self.complete:
return True
else:
pass
else:
pass
Or datetime.now().date()
from datetime import datetime
def is_end_date(self):
if datetime.now().date() > self.ending_date:
if not self.complete:
return True
else:
pass
else:
pass