【问题标题】:I have done something like this and it throws: UnboundLocalError at / local variable 'context' referenced before assignment error我做了这样的事情,它抛出:UnboundLocalError at / local variable 'context' referenced before assignment error
【发布时间】:2019-07-11 04:07:34
【问题描述】:

修改代码后:

class Index(FrontendMixin,TemplateView):
    template_name = "myapp/frontend/index.html"
def get_context_data(self,**kwargs):
    super().get_context_data(**kwargs)

    context = []

    if Post.objects.filter(deleted_at__isnull=True).count() > 1:
        context['Allpost'] = Post.objects.filter(publish=True).order_by('-created_at')
        context['mostrecentnews'] = News.objects.filter(publish=True, deleted_at__isnull=True).order_by('-created_at')[:1]
    else:
        context = []

    return {'context':context}

它抛出 TypeError at list indices must be integers or slices, not str error.

class Index(FrontendMixin,TemplateView):
    template_name = "myapp/frontend/index.html"
def get_context_data(self,**kwargs):
    super().get_context_data(**kwargs)

    if Post.objects.filter(deleted_at__isnull=True).count() > 1:
        context['Allpost'] = Post.objects.filter(publish=True).order_by('-created_at')
        context['mostrecentnews'] = News.objects.filter(publish=True, deleted_at__isnull=True).order_by('-created_at')[:1]
    else:
        context = []

    return {'context':context}

抛出:UnboundLocalError at / local variable 'context' referenced before assignment error

请建议摆脱这个错误

【问题讨论】:

  • 在第二个代码块中context 超出范围
  • 不,它在范围内,但我忘记分配超级调用的结果。我现在得到了答案。

标签: python django


【解决方案1】:

您忘记分配超级调用的结果。

context = super().get_context_data(**kwargs)

并将另一个分配删除到一个空列表中。

【讨论】:

    猜你喜欢
    • 2023-02-13
    • 1970-01-01
    • 2013-02-11
    • 2021-05-11
    • 1970-01-01
    • 2018-01-22
    • 2017-08-08
    • 1970-01-01
    • 2021-12-17
    相关资源
    最近更新 更多