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?
Every parameter that’s passed to the
as_viewmethod is an instance variable of the View class. That means to addslugas a parameter you have to create it as an instance variable in your sub-class:That should make
MyView.as_view(slug='hello_world')work.If you’re passing the variables through keywords, use what Mr Erikkson suggested: https://stackoverflow.com/a/11494666/9903