I'm trying to learn datetime and I'm currently trying to display all dates of November in an html template, in views I have:
year = today.year
month= today.month
num_days = calendar.monthrange(year, month)[1]
days = [datetime.date(year, month, day) for day in range(1, num_days 1)]
for days in days:
days_str = days.strftime('%A, %B, %d, %Y')
print(days_str)
context = {'': }
return render(request, 'template.html', context)
The output of the above is:
Monday, November, 01, 2021
Tuesday, November, 02, 2021
Wednesday, November, 03, 2021
Thursday, November, 04, 2021
Friday, November, 05, 2021
Saturday, November, 06, 2021
Sunday, November, 07, 2021
Monday, November, 08, 2021
Tuesday, November, 09, 2021
Wednesday, November, 10, 2021
Thursday, November, 11, 2021
Friday, November, 12, 2021
Saturday, November, 13, 2021
Sunday, November, 14, 2021
Monday, November, 15, 2021
Tuesday, November, 16, 2021
Wednesday, November, 17, 2021
Thursday, November, 18, 2021
Friday, November, 19, 2021
Saturday, November, 20, 2021
Sunday, November, 21, 2021
Monday, November, 22, 2021
Tuesday, November, 23, 2021
Wednesday, November, 24, 2021
Thursday, November, 25, 2021
Friday, November, 26, 2021
Saturday, November, 27, 2021
Sunday, November, 28, 2021
Monday, November, 29, 2021
Tuesday, November, 30, 2021
How to display above dates in a template?
CodePudding user response:
Simply place all dates in a list and pass the list to the context of the template.
year = today.year
month= today.month
num_days = calendar.monthrange(year, month)[1]
days = [datetime.date(year, month, day) for day in range(1, num_days 1)]
days_list = []
for days in days:
days_str = days.strftime('%A, %B, %d, %Y')
days_list.append(days_str)
context = {'days_list':days_list}
return render(request, 'template.html', context)
Then in your template
{% for day in days_list %}
{{day}}
{% endfor %}
Alternatively, you can pass the dates as datetime objects to the template and format them there using the Django built-in date filter.