Search code examples
djangodjango-generic-views

Additional params in URL for Django DetailView


In Django's documentation for DetailView, it shows URLs like:

  • url(r'^(?P<slug>[-\w]+)/$', ArticleDetailView.as_view(), name='article-detail'),
  • url(r'^(?P<pk>[-\w]+)/$', ArticleDetailView.as_view(), name='article-detail'),

That is, it only allows for either the keywords slug or pk. Is it possible to have an additional keywords in the URLs in addition to slug or pk, like:

url(r'^(?P<author_slug>[-\w]+)/(?P<slug>[-\w]+)/$', ArticleDetailView.as_view(), name='article-detail'),

Note the additional argument author_slug in the URL.


Solution

  • Yes, it is. You can access the additional kwargs via the kwargs dict in your view (assuming CBV).

    For example, in a class-based view, you could self.kwargs['memes']

    Note that this won't automatically say...do the object lookup for you (if you're writing a Detail View). You'd have to override get_object() for that.