【问题标题】:Django: sidebar with dynamic URLs: how to dynamically create URLs which have dynamic folders in the pathDjango:带有动态 URL 的侧边栏:如何动态创建路径中包含动态文件夹的 URL
【发布时间】: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


    【解决方案1】:

    只需将idcrawl_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('/') 获取这些数字。

    【讨论】:

    • 非常感谢!我使用了第二个选项,它就像一个魅力!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-02
    • 2018-04-03
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    相关资源
    最近更新 更多