Django:使用变量作为 URL 命名空间? [英] Django: Using a variable as the URL namespace?

查看:37
本文介绍了Django:使用变量作为 URL 命名空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为体育网站创建子菜单.每项运动都需要自己的子菜单.我遇到的问题是我需要命名空间本身在某种程度上是动态的.

I'm trying to create a submenu for a sports site. Each sport would need its own submenu. The problem I'm having is I need the namespace itself to be dynamic in someway.

SportListView 返回运动,因此我可以按运动过滤新闻文章.

SportListView returns the sport so I can then filter the news articles by the sport.

观看次数:

class SportListView(ListView):
    template_name="sports/sport-home.html"
    context_object_name='sport_list'

def get_context_data(self, **kwargs):
    context = super(SportListView, self).get_context_data(**kwargs)
    context['sport_menu'] = get_object_or_404(Sport, 
sport_slug=self.kwargs['sport_slug'])
    return context

模板:

<nav class="navbar navbar-expand-lg main-nav">
    <a href="{% url 'sports:sport-home' sport_menu.sport_slug %}">
    {{sport_menu.name}}</a>
    <a href="{% url sport_menu.sport_slug 'monthly' %}">Monthly View</a>
</nav>

子菜单中的第一个链接工作正常.正如您所看到的,它有效地充当了每项运动的主页按钮.

The first link in the submenu works fine. As you can see it effectively acts as a home button for each sport.

另一方面,第二个链接没有.在错误消息中,它返回了该运动的 slug,但我无法将其用作命名空间.

The second link does not on the other hand. In the error message it returns the slug of the sport but I can't get that to act as the namespace.

顺便说一下,我确实有一个应用程序及其 URLs.py 文件为当前的运动正确配置.所以我知道这不是问题.

I do have an app and its URLs.py file configured correctly for the current sport as well by the way. So I know that isnt the problem.

我在此配置中收到的当前错误消息是:

Current error message I'm getting withi this configuration is:

未找到板球"的反向.板球"不是有效视图函数或模式名称.

Reverse for 'cricket' not found. 'cricket' is not a valid view function or pattern name.

推荐答案

您可以使用 添加模板过滤器:

You can use the add template filter:

<a href="{% url sport_menu.sport_slug|add:':monthly' %}">Monthly View</a>

这篇关于Django:使用变量作为 URL 命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆