Django - Comparing Datetime Field With Server Time In Template Tags
I have an app with the following models.py file: from django.db import models import datetime class Event(models.Model): name = models.CharField(max_length=255) de
Solution 1:
You shouldn't create a today_date
field. It will be set to the default value when the object is created, but it won't be automatically updated each day.
today_date = models.DateField(default=datetime.date.today)
You could pass today's date as a variable from your view to the template context and do the comparison in the template, but it's better to keep the templates as simple as possible. A better approach would be to create a method on your model, e.g. is_future_event
:
from datetime import date
classEvent(models.Model):
event_date = models.DateField()
...
defis_future_event(self):
return self.event_date > date.today()
Then in your template, you can call the method as follows:
{% foreventin object_list %}
{% ifevent.is_future_event %}
Future event
{% else %}
Today orin the past
{% endif %}
{% endfor %}
Post a Comment for "Django - Comparing Datetime Field With Server Time In Template Tags"