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

后端 未结 7 816
悲哀的现实
悲哀的现实 2020-11-28 19:00

I have a custom class-based view

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

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


        
7条回答
  •  执念已碎
    2020-11-28 19:51

    Every parameter that's passed to the as_view method is an instance variable of the View class. That means to add slug as a parameter you have to create it as an instance variable in your sub-class:

    # myapp/views.py
    from django.views.generic import DetailView
    
    class MyView(DetailView):
        template_name = 'detail.html'
        model = MyModel
        # additional parameters
        slug = None
    
        def get_object(self, queryset=None):
            return queryset.get(slug=self.slug)
    

    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

提交回复
热议问题