【问题标题】:Two variables in Django URLDjango URL 中的两个变量
【发布时间】:2018-08-23 00:57:29
【问题描述】:

我想要一个类似这样的 URL:

/(category)/(post-slug)

在链接上,这是我所拥有的:

{% url blog.category blog.slug %}

对于 url.py:

url(r'^(I DON"T KNOW WHAT TO PUT ON THIS PART TO GET THE CATEGORY)/(?P<slug>[0-9A-Za-z._%+-]+)', views.post, name='post'),

谢谢

编辑: 这就是我现在所拥有的: 在 /

处仍有 NoReverseMatch 错误

urls.py

 url(r'^(?P<category>[0-9A-Za-z._%+-]+)/(?P<slug>[0-9A-Za-z._%+-]+)$', views.post, name='post'),

index.html

<a href="{% url blog.category blog.slug %}">

views.py

def post(request, slug, category):
    try:
        blog = Blog.objects.get(slug=slug)
    except Blog.DoesNotExist:
        raise Http404('This post does not exist')
    return render(request, 'parts/post.html', {
        'blog': blog,
    })

【问题讨论】:

  • 如果 URL 是 /(category)/(post-slug),那么 {% url category.blog category.slug %} 看起来是错误的。不应该是{% url post.category.slug post.slug %}之类的吗?
  • 抱歉,我刚才打错了,是的,我正在使用 blog.category 和 blog.slug,我的重点是正则表达式

标签: python regex django


【解决方案1】:

首先,您的 URL 标记需要您要反转的模式的名称作为第一个参数:

{% url 'post' blog.category blog.slug %}

或者如果您使用的是命名空间,例如:

{% url 'blog:post' blog.category blog.slug %}

您尚未展示您的视图或模型,因此我们只能猜测您的 URL 模式应该是什么。我不确定你为什么会觉得这个类别令人困惑——你只需要为组选择一个名称(例如category_slug)和组的正则表达式(你可能可以使用与@相同的名称) 987654324@)。那会给你:

url(r'^(?P<category_slug>[0-9A-Za-z._%+-]+)/(?P<slug>[0-9A-Za-z._%+-]+)$'

请注意,正则表达式的末尾应该有一个美元。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-04
  • 1970-01-01
  • 2014-01-31
  • 2019-10-27
  • 2011-08-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多