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

查看:53
本文介绍了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.

另一方面,第二个链接没有。在错误消息中,它返回了这项运动的内容,但我无法将其用作名称空间。

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.


推荐答案

您可以使用 add 模板过滤器:

You can use the add template filter:

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

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

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