Django反向错误:处的NoReverseMatch



你好,StackOverFlow成员,在我开门见山之前,让我在这里回顾一下我的想法/过程,以帮助进一步精简我的问题。当我在"location_tree.html"中单击一个位置对象时,它会将我重定向到一个新页面"location.html",显示位置名称及其类型。从同一个页面,名称将是指向另一个页面的超链接,其中包含有关"位置"的更多详细信息。

上面是我想要的一般流程,但当我试图从location.html点击名称时,它会将我重定向到这个错误:

/accounts/location/2处的NoReverseMatch/找不到关键字参数为"{u'pk":2}的"大陆"的反转。1>尝试的模式:[accounts/location/(?>P\d+)/location_content/(?P[d+)/']

需要注意的一些关键事项是,我使用的是python2.7。最后,当我从location.html中删除{%url%}时,一切都很好。这是我的工作代码,

应用程序/模型.py:

class Location(models.Model):
title = models.CharField(max_length=255)
location_type = models.CharField(max_length=255, choices=LOCATION_TYPES)
parent = models.ForeignKey("Location", null=True, blank=True, 
related_name="parent_location")
def __unicode__(self):
return self.title
class Continent(models.Model):
title = models.CharField(max_length=255)
location = models.OneToOneField(Location, on_delete=models.CASCADE, primary_key=True)
is_an_island = models.BooleanField(default=False)
def __unicode__(self):
return self.location.title

应用程序/视图.py:

def view_page_location(request, location_id):
location = Location.objects.get(id=location_id)
if location.location_type == 'Continent':
continent = Continent(location=location, is_an_island=False)
return render(request, 'accounts/location.html', {'location':location, 'continent':continent})
def view_continent(request, pk):
get_continent=get_object_or_404(Continent, pk)
return render(request, 'accounts/location_continent.html', {'get_continent':get_continent})

项目/uls.py:

from App.views import *
url(r'^accounts/location/(?P<location_id>d+)/', view_page_location, name='location'),
url(r'^accounts/location/(?P<location_id>d+)/location_continent/(?P<pk>d+)/', view_continent, name='continent'),

模板,

location_tree.html:

{% for child in locations %}
{% if child.parent == location %}
<ul>
<a href="{% url 'location' location_id=child.id %}">{{ child }}</a>

location.html:

{% if location.location_type == 'Continent' %}
<h2> Location: <a href="{% url 'continent' pk=location.pk %}">{{ location.title }}</a></h2>
<h3> Type: {{ location.location_type }} </h3></br>

location_continent.html:

<p> hello </p>

我离开了location_content,因为我想看看我是否能让它发挥作用。我觉得我的Urls.py中有些地方出了问题,或者可能我没有正确构建我的视图.py。

因此,最大的问题是,为了修复这个错误,我需要更改什么更改/修改?我自己看不见,所以我转向"你"。任何让我自己阅读并找到答案的链接也很感激。我希望我的问题是清楚而不含糊的。

两个问题。

location.html中的continenturl没有提供location_id参数,您只提供了pk。将其更改为类似的内容

<a href="{% url 'continent' location_id=location_id pk=location.pk %}">{{ location.title }}</a>

urls.py中,必须在locationurl的末尾添加$,否则locationcontinenturl之间会混淆。$在正则表达式中具有特殊含义,意味着它要求模式与字符串的末尾匹配。将URL更改为:

url(r'^accounts/location/(?P<location_id>d+)/$', view_page_location, name='location'),
url(r'^accounts/location/(?P<location_id>d+)/location_continent/(?P<pk>d+)/', view_continent, name='continent')

相关内容

最新更新