【发布时间】:2020-12-02 12:11:03
【问题描述】:
我在 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"),
如您所见,它们是采用 id 和 crawl_id 的动态 URL。因此,对于每个抓取仪表板,我希望侧边栏链接到其相关的 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 上下文正确地动态发送这些参数?
非常感谢!
【问题讨论】:
标签: python django django-templates django-urls