我正在尝试创建一个可以显示任务列表的日历网站。这里view.py
import calendar as calendar_engine # Используется calendar_engine что бы избежать колизий имен с моделькой
def render_calendar(request, path, year, month):
try:
calendar = Calendar.objects.get(path=path)
except Calendar.DoesNotExist:
return render(request, "Calendar/404.html", {"text": "calendar not found")
c = calendar_engine.Calendar()
tasks = {}
for weak in c.monthdatescalendar(year, month):
for date in weak: # date is datetime.date object
task = Task()
tasks[date] = task.get_day_tasks(date, calendar) # Функция возвращает список задач по конкретному дню. Её работоспособность гарантирована.
context = {"month": c.monthdatescalendar(year, month), "tasks": tasks}
return render(request, "Calendar/calendar.html", context)
calendar.html
<table>
{% for weak in month %}
<tr>
{% for date in weak %}
<th> {{ tasks[date] }} </th>
{% endfor %}
</tr>
{% endfor %}
</table>
但是,这不起作用,因为 jinja 会自动将datetime.date
对象转换为字符串 (date(2021, 1, 1) -> 1 Jan 2021)
. 由于字典中没有这样的键,KeyError
. 你能帮忙解决这个问题吗?
尝试将所有内容转换为字符串:
{'May 31, 2021': [], 'Jun 1, 2021': [<Task: Clementine Hopkins Placeat id id placeat eum harum sequi illo accusantium quidem aliquid tenetur dolorum ut et 1622540160>],
'Jun 2, 2021': [], 'Jun 3, 2021': [], 'Jun 4, 2021': [], 'Jun 5, 2021': [], 'Jun 6, 2021': [], 'Jun 7, 2021': [], 'Jun 8, 2021': [], 'Jun 9, 2021': [], 'Jun 10, 2021': [], 'Jun 11, 2021':
[], 'Jun 12, 2021': [], 'Jun 13, 2021': [], 'Jun 14, 2021': [], 'Jun 15, 2021': [], 'Jun 16, 2021': [<Task: Quincy Tyson Alias dolorem perferendis elit quam 1623806280>], 'Jun 17, 2021': .... Много заданий
但是又出现了一个错误:
django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '[date]' from 'tasks[date]'
jinja 不能与字典充分配合,所以我能想到的最好的方法是: