0

I am trying to compare the end date of an event with today's date to see if the event has ended. If the event has ended, the website user would not have a button to enrol and if the event has not started or is ongoing, the user would have a button to enrol in html.

I have tried this in my html template:

{% if event.end_date|date:"jS F Y H:i" <= today|date:"jS F Y H:i" %}
          {% include 'event/includes/enroll.html' %}

But the button shows whether or not the event has ended already.

I wanted to add a method in my django model like this:

@property
def is_today(self):
  return self.datefinish == datetime.today().date()

But I am not sure how to import the method and use it in html template then.

I wanted to try to add a variable in my view like this: (Django - Checking datetime in an 'if' statement)

is_today = model.end_date >= datetime.today()
return render_to_response('template.html', {'is_today': is_today})

But a colleague has written a Class-based view to render the template and not sure how to add the variable to render using the class-based view. I also got an error:

TypeError: '>=' not supported between instances of 'DeferredAttribute' and 'datetime.datetime'

If anyone can advice on how to best achieve what I need, I would be grateful :D

luigigi
  • 4,146
  • 1
  • 13
  • 30
MPia K
  • 1

1 Answers1

0

Hello why dont you use a custom_filter, that will return True or False in your template ? (https://docs.djangoproject.com/fr/3.1/howto/custom-template-tags/):

import datetime
from django import template
from django.conf import settings


register = template.Library()


@register.filter
def event_ended(date_event):
    return date_event >= datetime.date.today()
{% load poll_extras %}
{% if event.end_date | event_ended %}
    {% include 'event/includes/enroll.html' %}

The link from the documentation told you where to put the custom template

MaximeK
  • 2,039
  • 1
  • 10
  • 16
  • Thanks @maximeK I have tried to implement this just now with a templatetag in my_tags.py and {% load my_tags %} in my template. But it is still ignoring the ended date which I've printed and tested and not showing the button to enroll, whether the event has ended or not – MPia K Oct 30 '20 at 12:00
  • I actually got it, forgot to add .date() behind date_event to remove the time. All working now! thanks again – MPia K Oct 30 '20 at 12:07