13

我在配置我的 url 以显示详细视图时遇到问题。单击此链接:<a href='{% url blog_detail blog.slug %}'>{{ blog.name }}</a>显示blog.html,当我认为它会显示时blog-detail.html。没有错误,浏览器栏显示:example.com/blog/the-slug,但仍显示来自 的 html blog.html,而不是blog-detail.html。任何想法为什么?谢谢你的想法。

网址:

url(r'^blog/', 'myapp.views.blog', name='blog'),
url(r'^blog/(?P<slug>[\w-]+)/$', 'myapp.views.blog_detail', name='blog_detail'),

意见:

def blog(request):
    blog_list = Blog.objects.all()
    return render(request, 'blog.html', {'blog_list':blog_list})

def blog_detail(request, slug):
    blog = get_object_or_404(Blog, slug=slug)
    return render(request, 'blog-detail.html', {'blog':blog})

编辑:@omouse 要求的输出

这是单击链接的输出。它与 完全相同blog.html,但应该如此blog-detail.html

<div id='content-wrapper'>
<section>
<div class='blog-name'><h2><a href='/blog/test/'>Test</a></h2></div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry&#39;s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a ...

<div class='blog-name'><h2><a href='/blog/second-test/'>Second Test</a></h2></div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry&#39;s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a ...
</section>
</div>
4

2 回答 2

28

网址是问题,第一个将匹配所有内容(/blog/, /blog/test/, ),您需要它末尾/blog/awdlawdjaawld的美元符号才能匹配。$/blog/

url(r'^blog/$', 'myapp.views.blog', name='blog'),
url(r'^blog/(?P<slug>[\w-]+)/$', 'myapp.views.blog_detail', name='blog_detail'),

以上应该可以正常工作。

这是正则表达式的一个很好的参考

于 2013-02-26T02:41:35.530 回答
0

鲁道夫完全正确

停止的/$博客捕获所有由 slug 调用的子页面,因此如果您有子页面,您需要添加/$到文件夹级别,如下所示:

re_path('brands/$', AllBrands.as_view(), name="brands"),
re_path(r'^brands/(?P<slug>[\w-]+)/$', BrandDetail.as_view(), name = 'brandetail'),

这是 django 2.2

没有/$品牌之后,slug 页面显示的是品牌列表页面。

于 2019-11-08T23:32:24.267 回答