2

我正在 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) ...

有人有解决方案吗?谢谢~

4

1 回答 1

1

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

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

于 2013-08-17T21:58:51.567 回答