上下文必须是dict而不是列表呈现模板

2024-10-04 11:33:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在和django做一个问答游戏。现在我在渲染模板时遇到了一个小问题。它返回了这个错误“上下文必须是dict而不是list”。我知道上下文应该作为dict返回,我在context['cursos']行中怀疑。谁能确认我的嫌疑犯或给我一些解决办法?提前谢谢

class ListCursos( TemplateView):
    model1 = User
    model2 = Course
    template_name = 'plantillas/miscursos.html'

    def get_context_data(self, *args, **kwargs):
        context = super(ListCursos, self).get_context_data(**kwargs)
        rels = CourseRelUser.objects.filter(user_id=1)
        courses_id=[]
        for rel in rels:
            courses_id.append(rel.c_id)
            return courses_id

        context['cursos'] = Course.objects.filter(id__in=courses_id)
        return context
        

以下是完整的回溯错误:https://i.stack.imgur.com/oVseL.png

    Internal Server Error: /core/miscursos/
Traceback (most recent call last):
  File "C:\Users\juand\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\juand\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response
    response = response.render()
  File "C:\Users\juand\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\response.py", line 105, in render
    self.content = self.rendered_content
  File "C:\Users\juand\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\response.py", line 83, in rendered_content
    return template.render(context, self._request)
  File "C:\Users\juand\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\backends\django.py", line 59, in render
    context = make_context(context, request, autoescape=self.backend.engine.autoescape)
  File "C:\Users\juand\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\context.py", line 268, in make_context
    raise TypeError('context must be a dict rather than %s.' % context.__class__.__name__)
TypeError: context must be a dict rather than list.
[20/Jan/2021 11:08:22] "GET /core/miscursos/ HTTP/1.1" 500 76063

Tags: djangoinselfidresponseliblocalcontext
1条回答
网友
1楼 · 发布于 2024-10-04 11:33:23

好的,那么遵循爱德华多的观点。我证明了从for循环中删除return courses_id,效果很好

class ListCursos( TemplateView):
model1 = User
model2 = Course
template_name = 'plantillas/miscursos.html'

def get_context_data(self, *args, **kwargs):
    context = super(ListCursos, self).get_context_data(**kwargs)
    rels = CourseRelUser.objects.filter(user_id=1)
    courses_id=[]
    for rel in rels:
        courses_id.append(rel.c_id)

    context['cursos'] = Course.objects.filter(id__in=courses_id)
    return context

相关问题 更多 >