反向显示url通用视图

问题描述

| 该主题是本主题中思想的延续。我回避了通用视图中的反向问题。上一次我认为这不是反向匹配,因为我使用了很多对很多,现在我没有太多的反向关系,但是问题仍然存在。由于我在两种情况下都具有通用视图,因此我建议问题出在通用视图中,而没有视图功能。  首先,我在模型中使用了@permalink装饰器
...
@permalink
def get_absolute_url(self):
    return (\'categories\',str(self.id))
...
@permalink
def get_absolute_url(self):
    return (\'pages\',(),{\'page_name\': self.human_readable_url})
网址
url(r\'^(?P<page_name>&\\w*)?/?$\',direct_to_template,{\'template\': \'basic.djhtml\'},name = \"pages\"),url(r\'cat/\\d+/$\',name = \"categories\")
并得到一个错误:   noreverseMatch:使用参数\'()\'和关键字参数\'{\'page_name \':u \'page1 \'} \'找不到\'pages \'的反向。 然后我尝试了反向方法
def get_absolute_url(self):
    return reverse(\'categories\',args = [self.id,])
并且有相同的错误   noreverseMatch:找不到带有参数\'(2,)\'和关键字参数\'{} \'的\'categories \'。 基于永久链接未明确使用反向方法这一事实,我认为问题出在交互反向和url中的通用视图。为什么会这样呢?如何在URL通用视图中使用反向?     

解决方法

        问题是,您给通用视图Direct_to_template指定了名称
categories
,并且正在向该视图传递参数-但是direct_to_template不采用该参数,只有一个包含额外上下文的字典。 如果要将其他参数传递给通用视图,则可以-但它们只会传递给模板。您可以通过编写自己的函数来扩展视图,该函数将参数添加到字典中,然后调用通用视图。像这样:
# views.py
from django.views.generic.simple import direct_to_template

def my_view(id):
    more_data = {\'id\': id}
    return direct_to_template(template = \'basic.djhtml\',more_data)
然后在
urls.py
中,将
direct_to_template
换成
my_view
。由于
my_view
需要一个
id
参数,因此
reverse
会正确匹配它,并且该参数将传递给通用视图,然后传递给模板。 大概模板中的某处是一行,例如
{{ id }}
。