【问题标题】:UnboundLocalError at / local variable 'context' referenced before assignmentUnboundLocalError at / local variable 'context' 在赋值之前引用
【发布时间】:2020-12-01 04:11:20
【问题描述】:

在我的 Django 应用程序中使用 views.py 出现此错误 - UnboundLocalError 在 / 赋值前引用的局部变量“上下文”。

这里是一个不工作的代码的 sn-p:

from django.shortcuts import render
from .models import *

def store(request):
products = Product.objects.all()
context: {'products':products}
return render(request, 'store/store.html', context) 

【问题讨论】:

  • context 在您引用它之前未在任何地方定义,正如错误消息所述。我相信你犯了一个简单的错字,context: {'products':products} -> context = {'products':products} 否则你所拥有的是一个变量 type annotation 而不是赋值语句
  • 这是错字,谢谢指出。现在效果很好。

标签: python django django-views


【解决方案1】:

尝试以下方法:

from django.shortcuts import render
from .models import *

def store(request):
products = Product.objects.all()
context = {'products':products} #I have changed : to =
return render(request, 'store/store.html', context) 

【讨论】:

  • 谢谢。我的错,现在效果很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-11
  • 2011-05-02
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 1970-01-01
相关资源
最近更新 更多