【发布时间】: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超出范围 -
不,它在范围内,但我忘记分配超级调用的结果。我现在得到了答案。