How to loop over datetime range in django templates

3k Views Asked by At

I want to loop from current date to xxx date in columns I'm thinking about using this function:

from datetime import timedelta, date


def daterange(start_date, end_date):
    start_date = datetime.date.today()
    end_date = start_date + datetime.timedelta(days=5)
    for n in range(int((end_date - start_date).days)):
        yield start_date + timedelta(n)



for single_date in daterange(start_date, end_date):
    print single_date.strftime("%Y/%m/%d")

But I don't know how to pass it to context in views.py

I want something like this, but in days:

enter image description here

2

There are 2 best solutions below

6
On BEST ANSWER

You can solve it using custom template tag:

Firstly create the file structure. Go into the app directory where the tag is needed, and add these files:

templatetags

templatetags/init.py

templatetags/custom_tags.py

The templatetags/custom_tags.py file:

from django import template

register = template.Library()

@register.daterange
def daterange(start_date, end_date):
    start_date = datetime.date.today()
    end_date = start_date + datetime.timedelta(days=5)
    for n in range(int((end_date - start_date).days)):
        yield start_date + timedelta(n)

The template part:

{% load custom_tags%}


{%for date_out in start_date|daterange:timedelta %}
   <!-- do something here with date_out -->
{% endfor %}
1
On

I got another way to do it:

Just use pass this function to context 'daterange': daterange()

def daterange(start_date, end_date):
    start_date = datetime.date.today()
    end_date = start_date + datetime.timedelta(days=5)
    for n in range(int((end_date - start_date).days)):
        yield start_date + timedelta(n)

and in your template:

{% for i in date_range %}
...
{% endfor %}