传递参数查看但不使用

Pass parameters to view but not using them

我有一个看法:

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_idslug,我应该通过它们吗?我通过了人类可读 url。 Url 示例:http://127.0.0.1:8000/brands/1/coca_cola/3/

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')

如果您不需要这些参数,您可以将它们设为视图的可选参数并将它们留在 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'),
                       )

注意“?”在前两个匹配的正则表达式之后,使它们成为可选的。这意味着您可以将它们排除在视图之外,但 reverse('product_detail', brand_id, slug, product_id) 仍然 return 清晰易读 URL.