我有一个观点:
def product_details(request, brand_id, slug, product_id):
product = get_object_or_404(Product, id=product_id)
return render(request, 'product_details.html',
{'product': product})
urls.py
:
urlpatterns = patterns('',
url(r'^$', 'core.views.show_brands', name='brands'),
url(r'^(?P<brand_id>\d+)/(?P<slug>[-\w\d]+)/$', 'core.views.brand_products', name='brand_products'),
url(r'^(?P<brand_id>\d+)/(?P<slug>[-\w\d]+)/(?P<product_id>\d+)/$', 'core.views.product_details', name='product_detail'),
)
问题是:如果我不使用它们,我应该通过brand_id
和slug
吗?我通过了人类可读的网址。网址示例:http://127.0.0.1:8000/brands/1/coca_cola/3/
答案 0 :(得分:0)
views.py
def product(request, id, slug):
context = {}
context['product'] = get_object_or_404(Product, id=id, slug=slug)
return render(request, 'html', context)
urls.py
url(r'^product/(?P<slug>\w+)/(?P<id>\d+)/$', views.product, name='product')
答案 1 :(得分:0)
如果您不需要参数,可以将它们作为视图的可选项,并将其保留在URL中,如下所示:
def product_details(request, product_id):
product = get_object_or_404(Product, id=product_id)
return render(request, 'product_details.html',
{'product': product})
urls.py:
urlpatterns = patterns('',
url(r'^(\d+)?/([-\w\d]+)?/(?P<product_id>\d+)/$', 'core.views.product_details', name='product_detail'),
)
注意&#34;?&#34;在前两个匹配的正则表达式之后,使它们成为可选的。这意味着您可以将它们排除在视图之外,但反向(&#39; product_detail&#39;,brand_id,slug,product_id)仍将返回一个清晰的URL。