python - Django - 通过 URL 将属性从 utils.py 传递到模板
问题描述
我无法将 utils.py 中的属性传递给模板
- 将属性作为 URL 传递并在模板中读取(通过 URL,因为我不太了解)
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 是否正确。
解决方案
自我回答:刚刚将urls.py 中的url切换到path并且它现在正在运行。
https://docs.djangoproject.com/en/3.1/topics/http/urls/ 我使用的是已弃用的代码
推荐阅读
- amazon-ec2 - 如何为新的 AWS 实例增加或添加存储(最多 500Gb)?
- kubernetes - 入口资源未路由正确公开的服务
- c# - 连接到 NetSuite Web 服务时出现 SOAP 错误:“未定义命名空间前缀 'soapenv'”
- mongodb - mongo 和 laravel 之间没有使用 docker 的连接
- testing - 拥有 1000 多个节点的 Jenkins 性能 - 自己的设备场
- javascript - TypeError: $(...).on 不是prototype.js 的函数
- react-native - 集成(Redux 与本机反应)
- android - 在 Oreo 中将位图重力设置为底部离开屏幕层列表
- javascript - 验证表单上的两个字段
- mysql - 在 sql developer 中更改连接 url