0

I have a model very imaginatively called 'model' which has a field 'datefinish' in it; users can input a date here in the format MM/DD/YYYY. In my template I need some text displayed when said model has a datefinish (date) that is equal to the current day.

HTML:

{% if model.datefinish == datetime.today %}
   <h5>It ends today</h5>
{% else %}
   <h5>It does not end today</h5>
{% endif %}

How might one achieve this? I'm using Django 1.10...thanks!

jayt
  • 758
  • 1
  • 14
  • 32

3 Answers3

3

The model option as per Daniel's suggestion, which I prefer as then you have it always available whenever you load that model

in the mode:

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

this assumes that the 'datefinish' is a DateField, not a DateTimeField, for DateTimeField you would do self.datefinish.date() == ...

you can also see if its within a range, i.e.

return self.start_date <= datetime.today().date() <= self.end_date

if you have two dates in a model.

or create a template tag like:

@register.filter
def is_today(dt):
  if isinstance(dt, datetime):
    return dt.date() == datetime.today().date():
  if isinstance(dt, date):
    return dt == datetime.today().date():

then in the template you can do

{% if model.datetime_field|is_today %}

The filter can handle DateField and DateTimeField

warath-coder
  • 2,087
  • 1
  • 17
  • 21
0

Don't do this in the template. Write a method on the model - called for example finishes_today - that does this check and returns a boolean, and call that in the template.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

I would avoid overloading templates with logic and put this check into the view (or as a model property as suggested by Daniel):

is_today = model.datefinish == datetime.today()

return render_to_response('template.html', {'is_today': is_today})

Then, in your template simply check the variable passed in the context:

{% if is_today %}
   <h5>It ends today</h5>
{% else %}
   <h5>It does not end today</h5>
{% endif %}

There is also this option, but it does look a bit overly complicated.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195