基于django类的视图出错:'get_context_data()关键字必须是字符串'

时间:2013-08-17 17:03:10

标签: python django listview web

我正在django网站上进行迁移,我将list_object视图重写为基于类的视图,该视图继承自django.views.generic.ListView,但是当我创建get_context_data方法时出现错误

我的代码在这里:

class ForumView(ListView):
    context_object_name = 'forum'
    template_name = 'forum/thread_list.html',
    paginate_by = FORUM_PAGINATION
    def get_queryset(self):
        try:
            f = Forum.objects.for_groups(self.request.user.groups.all()).select_related().get(slug=self.kwargs['slug'])
        except Forum.DoesNotExist:
            raise Http404
        return f.thread_set.select_related().all()
    def get_context_data(self, **kwargs):
        try:
            f = Forum.objects.for_groups(self.request.user.groups.all()).select_related().get(slug=self.kwargs['slug'])
        except Forum.DoesNotExist:
            raise Http404
        form = CreateThreadForm()
        child_forums = f.child.for_groups(self.request.user.groups.all())
        extra_context = {
            'forum': f,
            'child_forums': child_forums,
            'form': form,
            'login': {
                'reason': _('create a new thread'),
                'next': f.get_absolute_url(),
            },
            'section': 'forum',
        }
        context = super(ForumView, self).get_context_data(**kwargs)
        for key in extra_context:
            context[key] = extra_context[key]
        return context

和url.py

url(r'^thread/(?P<thread>[0-9]+)/$', ThreadView.as_view(), name='forum_view_thread'),

但是django返回一个调试页面:

Exception Value: get_context_data() keywords must be strings
Python Version: 2.7.3
Django Version: 1.5.2
Request URL: http://localhost:8000/forum/thread/1/
Exception Location: /Library/Python/2.7/site-packages/django/views/generic/list.py in get_context_data, line 116

traceback:
/Library/Python/2.7/site-packages/django/core/handlers/base.py in get_response
                    response = callback(request, *callback_args, **callback_kwargs) ...

/Library/Python/2.7/site-packages/django/views/generic/base.py in view
        return self.dispatch(request, *args, **kwargs) ...

/Library/Python/2.7/site-packages/django/views/generic/base.py in dispatch
    return handler(request, *args, **kwargs) ...

/Library/Python/2.7/site-packages/django/views/generic/list.py in get
    context = self.get_context_data(object_list=self.object_list) ...

/Users/foulwall/Dropbox/mldata/forum/views.py in get_context_data
    context = super(ThreadView, self).get_context_data(**kwargs) ...

/Library/Python/2.7/site-packages/django/views/generic/list.py in get_context_data
    return super(MultipleObjectMixin, self).get_context_data(**context) ...

有解决方案的人吗?感谢〜

1 个答案:

答案 0 :(得分:1)

我怀疑你发送给get_context_data的一个kwargs不是一个简单的字符串对象。这可以作为kwargs字典中的键传递。也许它是一个懒惰或可翻译的字符串?

this question的人发生了类似的事情。如果它是同一个问题,我建议你确保变量名称确实是一个简单的字符串。变量名中的Unicode字符很奇怪,但可接受的顺便说一句。