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

后端 未结 7 854
悲哀的现实
悲哀的现实 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条回答
  •  旧时难觅i
    2020-11-28 19:53

    If you want to add an object to the context for the template you can override get_context_data and add to its context. The request is also a part of self in case you need the request.user.

    def get_context_data(self, **kwargs):
            context = super(MyTemplateView, self).get_context_data(**kwargs)
            if 'slug' in self.kwargs:
                context['object'] = get_object_or_404(MyObject, slug=self.kwargs['slug'])
                context['objects'] = get_objects_by_user(self.request.user)
    
            return context
    

提交回复
热议问题