如何解决Django:具有动态URL的侧栏:如何动态创建在路径中具有动态文件夹的URL
我在Django的侧边栏导航中使用动态URL时遇到问题,希望大家能帮助我阐明如何解决它。我一直在寻找类似的问题,但找不到我的案子的答案。
基本上,我要实现的是要有一个带有链接的边栏。此边栏将在许多页面上重复使用,因此它位于单独的sidebar.py文件中,该文件随后会导入到页面中。
<h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
<span>Content</span>
<a class="d-flex align-items-center text-muted" href="#">
<span data-feather="plus-circle"></span>
</a>
</h6>
<ul class="nav flex-column">
<li class="nav-item">
<a class="nav-link active" href="DYNAMIC LINK HERE">
<span data-feather="home"></span>
Status codes</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">
<span data-feather="file"></span>
Depth
</a>
</li>
</ul>
我要显示的链接如下:
urls.py
path('<id>/<crawl_id>/dashboard/',ProjectDashboard,name="crawl_dashboard"),path('<id>/<crawl_id>/dashboard/status-codes/',StatusCodeDashboard,name="status_code_dashboard"),path('<id>/<crawl_id>/dashboard/url-depth/',UrlDepthDashboard,name="url_depth_dashboard"),
如您所见,它们是动态URL,带有id和crawl_id。因此,对于每个爬网仪表板,我希望边栏链接到其相对的status_code_dashboard页面和url_depth_dashboard页面。
例如:
/22/123/dashboard --> should have a sidebar with links to:
/22/123/dashboard/status-code/
/22/123/dashboard/url-depth/
我试图做的是创建一个如下所示的上下文处理器:
def get_dashboard_paths(request):
# Get current path
current_path = request.get_full_path()
depths_dashboard = current_path + 'url-depth/'
return {
'depths_dashboard': depths_dashboard
}
...然后在sidebar.py模板中使用{{depths_dashboard}} ...
这有效,但是它不可扩展:例如,当我在/ 22/123 / dashboard / status-code /中时,我仍然希望有侧边栏链接到其他部分。如果我使用上述上下文处理器,由于解决方案不正确,将会创建错误的链接,例如:
/22/123/dashboard/status-code/status-code/
/22/123/dashboard/status-code/url-depth/
您是否暗示了如何使用基于id和crawl_id的动态URL在上述所有页面上显示侧边栏?基本上,问题是,如何根据我所在的id和crawl_id上下文动态地正确发送这些参数?
非常感谢!
解决方法
只需将id
和crawl_id
传递到模板中即可。然后在模板中:
<a href="/{{ id }}/{{ crawl_id }}/dashboard">Dashboard</a>
<a href="/{{ id }}/{{ crawl_id }}/dashboard/status-code">Status code</a>
<a href="/{{ id }}/{{ crawl_id }}/dashboard/url-depth">URL depth</a>
如果您特别想使用预处理器,还可以从get_full_path().split('/')
获取这些数字。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。