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

后端 未结 7 849
悲哀的现实
悲哀的现实 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:37

    As stated by Yaroslav Nikitenko, if you don't want to hardcode a new instance variable to the View class, you can pass extra options to view functions from urls.py like this:

    url(r'^$', YourView.as_view(), {'slug': 'hello_world'}, name='page_name')
    

    I just wanted to add how to use it from the view. You can implement one of the following methods:

    # If slug is optional
    def the_function(self, request, slug=None):
        # use slug here
    
    # if slug is an optional param among others
    def the_function(self, request, **kwargs):
        slug = kwargs.get("slug", None)
        other_param = kwargs.get("other_param", None)
    
    # If slug is required
    def the_function(self, request, slug):
        # use slug here
    

提交回复
热议问题