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

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

    It's worth noting you don't need to override get_object() in order to look up an object based on a slug passed as a keyword arg - you can use the attributes of a SingleObjectMixin https://docs.djangoproject.com/en/1.5/ref/class-based-views/mixins-single-object/#singleobjectmixin

    # views.py
    class MyView(DetailView):
        model = MyModel
        slug_field = 'slug_field_name'
        slug_url_kwarg = 'model_slug'
        context_object_name = 'my_model'
    
    # urls.py
    url(r'^(?P[\w-]+)/$', MyView.as_view(), name = 'my_named_view')
    
    # mymodel_detail.html
    {{ my_model.slug_field_name }}
    

    (both slug_field and slug_url_kwarg default to 'slug')

提交回复
热议问题