Django class-based view: How do I pass additional parameters to the as_view method?

user9903 picture user9903 · Jul 15, 2012 · Viewed 94.2k times · Source

I have a custom class-based view

# myapp/views.py
from django.views.generic import *

class MyView(DetailView):
    template_name = 'detail.html'
    model = MyModel

    def get_object(self, queryset=None):
        return queryset.get(slug=self.slug)

I want to pass in the slug parameter (or other parameters to the view) like this

MyView.as_view(slug='hello_world')

Do I need to override any methods to be able to do this?

Answer

Daniel Eriksson picture Daniel Eriksson · Jul 15, 2012

If your urlconf looks something like this:

url(r'^(?P<slug>[a-zA-Z0-9-]+)/$', MyView.as_view(), name = 'my_named_view')

then the slug will be available inside your view functions (such as 'get_queryset') like this:

self.kwargs['slug']