首页 > 解决方案 > Django - 通过 URL 将属性从 utils.py 传递到模板

问题描述

我无法将 utils.py 中的属性传递给模板

utils.py 正在创建一个月历表,并且每个月的每一天都会循环检查每个房间每天有多少个插槽可供预订(这部分很好)。我正在尝试将这一天传递给每日日程模板。这部分只有在我添加属性时才会运行。只需每天链接到同一个模板。

utils.py 

# check available slots per room for that day / return room_name and free_slots

for rooms in rooms_list:
    
        slot_calculation = 5 - Room.objects.filter(event__room = rooms, event__start_time__day=day).count()
        d += f'<br>{rooms.get_roomlist} {slot_calculation}</li>'

# create a hyperlink for each day cell to template calendar_rooms
url = reverse("cal:calendar_rooms") <--- #how do I pass the attribute right here?
return f'<td><span class="date"><a href="{url}">{day}</a></span><ul> {d} </ul></td>' 

只要我不在 urls.py 中添加 <attr>,调用模板就会运行

urls.py
url(r'^calendar_rooms/<attr>/$', views.cal_rooms, name='calendar_rooms'),

View.py 应该接受 http://localhost:800/calendar_rooms/20200101/ 之类的输入,但我得到的只是404 - 使用 hot_django.urls 中定义的 URLconf,Django 按以下顺序尝试了这些 URL 模式: 我尝试了HttpResponse 也是如此。

view.py 
# how do I pass an attribute?

def cal_rooms(request, attr):    
context = {
    'attr': attr,
}
return render(request, 'cal/calendar_rooms.html', context)

我尝试了各种解决方案都无济于事。我不确定通过 URL 传递 attr 是否正确。

标签: pythondjangotemplatesurl

解决方案


自我回答:刚刚将urls.py 中的url切换到path并且它现在正在运行。

https://docs.djangoproject.com/en/3.1/topics/http/urls/ 我使用的是已弃用的代码


推荐阅读