【问题标题】:Django Url, Slug for Detail PageDjango Url,详细页面的 Slug
【发布时间】:2013-02-11 08:53:51
【问题描述】:

我在配置我的 url 以显示详细视图时遇到问题。单击此链接:<a href='{% url blog_detail blog.slug %}'>{{ blog.name }}</a> 显示blog.html,而我认为它会显示blog-detail.html。没有错误,浏览器栏显示:example.com/blog/the-slug,但仍显示来自blog.html 的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>

【问题讨论】:

  • 试试这个{{ blog.name }}
  • 是的,已经尝试过了,谢谢。仍然没有运气。不知道可能是什么问题...
  • 你能添加模板输出是什么吗?
  • 感谢@omouse:模板输出为blog.html。它只是虚拟文本,但我已将其包含在上面。

标签: django slug urlconf


【解决方案1】:

鲁道夫完全正确

/$ 阻止博客捕获所有被 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 页面显示的是品牌列表页面。

【讨论】:

    【解决方案2】:

    网址是问题,第一个会匹配所有内容(/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'),
    

    以上应该可以正常工作。

    This is a good reference for Regular Expressions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-30
      • 2019-08-14
      • 2014-05-31
      • 2015-04-19
      • 2013-04-02
      • 2022-01-22
      • 2021-07-04
      • 2014-11-13
      相关资源
      最近更新 更多