【问题标题】:How to use dynamic urls on templates如何在模板上使用动态网址
【发布时间】:2017-02-08 07:08:43
【问题描述】:

我使用 python 2.7.11 和 django 1.10.2。我创建了 url 并使用了动态模板。

urls.py

url(r'^suits-anarkali/', include([
                url(r'^$', category_page, name="suits-anarkali"),
                url(r'^(?P<slug>[\w-]+)/$', category_page, name="suits-anarkali"),
                url(r'^(?P<slug>[\w-]+)/$', single_product, name='singleproduct'),
                url(r'^(?P<slug>[\w-]+)/(?P<singleproduct_slug>[\w-]+)/$', singleproduct, name="singleproduct"),
    ])
),

这是我的网址结构。如果我用 slug 调用 category_page 那么它工作正常但是当我用 slug 调用 single_product 时它会重定向到类别页面。 我已经尝试了很多时间,但它不起作用。那么如何管理模板上的url呢?

product.html

{% if slug %}
    <a href="{% url 'singleproduct' slug detail.slug %}">{{ detail.product_name }}</a>
{% else %}
    <a href="{% url 'singleproduct' detail.slug %}">{{ detail.product_name }}</a>
{% endif %}

【问题讨论】:

  • 请在询问前检查我们的拼写。我更正了两个错别字。

标签: python django django-views django-urls


【解决方案1】:

urls 在第一次匹配正则表达式的基础上工作,并且由于下面的两行都匹配完全相同的 slug 参数,所以当您使用 slug 调用 url 时,首先匹配的是 category_page,因此 django 不会继续检查下一行。您需要对category_page 进行一些更改,使其与其他正则表达式不同。

    url(r'^(?P<slug>[\w-]+)/(?P<product>[\w-]+)/$', single_product, name='singleproduct'),
    url(r'^(?P<slug>[\w-]+)/$', category_page, name="suits-anarkali"),

read more on url tag

【讨论】:

  • 是的,下面的两行都匹配完全相同的 slug 参数。但名称和视图不同。所以它可以正常工作。如果可能的话,那么我的代码会发生什么变化。
  • 是的,我只是想让您注意这个问题。您可以更改其中之一以避免不必要的模式匹配。
  • @ zumba 是的先生,但我需要两个 url 因为 category_page 视图显示类别和子类别 product_list 列表。而single_product view显示分类产品详情,singleproduct view显示子分类产品详情。
猜你喜欢
  • 2013-06-09
  • 2011-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多