Pass a captured named regular expression to URL dictionary in generic view
I am working with a generic view in Django. I want to capture a named group parameter in the URL and pass the value to the URL pattern dictionary. For example, in the URLConf below, I want to capture the parent_slug
value in the URL and pass it to the queryset dictionary value like so:
urlpatterns = patterns('django.views.generic.list_detail',
(r'^(?P<parent_slug>[-\w]+)$',
'object_list',
{'queryset':Promotion.objects.filter(category=parent_slug)},
'promo_promotion_list',
),
)
Is this possible to do in one URLConf entry, or would it be wiser if I create a custom view to capture the value and pass the queryset directly to the generic 开发者_StackOverflow中文版view from my overridden view?
I'm doing some redirects in urls.py as follows, maybe that works for you too?
from django.views.generic.base import RedirectView
urlpatterns = patterns('',
(r'^manual/glossary/(?P<slug>[^/]+)/$',
RedirectView.as_view(url='/glossary/%(slug)s/')),
)
However, that seems not to be supported by all class based generic views:
from django.views.generic.list import ListView
urlpatterns = patterns('',
(r'^tag/(?P<tag>\d+)/$',
ListView.as_view(
queryset=Blog.Post.objects.filter(tags='%(tag)d'),
paginate_by=5)),
)
This second code snipplet does not work, so you would have to patch the generic ListView or pass via a custom view as you proposed.
精彩评论