Django ListView __init__接受关键字参数

时间:2014-01-29 15:00:53

标签: python django listview

我写过这个Django ListView(我不是很熟悉),我试图使用 init 覆盖基于slug输入的变量。不知怎的,似乎 init 函数无法访问关键字参数。调度功能完成工作就好了,我仍然想知道为什么 init 不起作用。有什么想法吗?

代码:

Views.py

from django.views.generic import ListView
form models import MyModel

class MyListView(ListView):
    model = MyModel
    template_name = 'index.html'

    # does not work
    def __init__(self, **kwargs):
        print kwargs
        return super(MyListView, self).__init__(**kwargs)

    # works
    def dispatch(self, request, *args, **kwargs):
        print self.kwargs
        return super(MyListView, self).dispatch(request, *args, **kwargs)

    def get_queryset(self):
        # filter for data based on category_slug input

    def get_context_data(self, **kwargs):
        context = super(MyListView, self).get_context_data(**kwargs) 
        return context      

Urls.py:

url(r'^browse/(?P<category_slug>[a-zA-Z0-9-]+)', MyListView.as_view(), name='browse-category'),

1 个答案:

答案 0 :(得分:1)

因为它们是基于类的,所以您可以通过self访问班级中任何位置的关键字参数:

def get_queryset(self):
    # filter for data based on category_slug input
    categories = self.model.objects.filter(slug=self.kwargs['category_slug'])
    ...
    return categories