python - UnboundLocalError-赋值前引用的局部变量“app”
问题描述
bu beim appname.urls kodlarım [appname: atolye (bu bir Türk kelimesi)]
从 django.conf.urls 导入 url 从 .views 导入 * urlpatterns = [
url(r'^index/$', atolye_index),
url(r'^(?P<id>\d+)/$', atolye_detail),
] ve bu benim atolye.views
从 django.shortcuts 导入渲染,get_object_or_404 从 .models 导入 atolye
def atolye_index(request): atolyes=atolye.objects.all() return render(request, 'atolye_index.html', {'atolyes':atolyes})
def atolye_detail(request, id): atolye = get_object_or_404(atolye, id=id) context = { 'atolye': atolye, } return render(request, 'atolye_detail.html', context) Bu kodu kullanmak istiyorum ama işe yaramıyor。内亚普马勒伊姆?
python:3.5.3 django:1.10 win7 Yeni bir kullanıcıyım。Kötü ingilizcem için özür dilerim。
解决方案
我在这里进行了一些猜测,因为您的异常回溯与您的标题或描述都不匹配,并且您的代码不可读,但是……</p>
from .models import atolye
# …
def atolye_detail(request, id):
atolye = get_object_or_404(atolye, id=id)
最后一行可能是例外,未绑定的本地可能不是app
或您提到的另一行但是atolye
,对吗?
问题是,如果您在函数中的任何位置指定名称,则该名称始终是该函数中的局部变量。
所以,既然你在atolye =
这里,atolye
就是一个局部变量。即使在get_object_or_404(atolye, id=id)
. 而且,由于该调用发生在您为 分配任何内容之前atolye
,因此局部变量没有任何值。
我不确定您要在这里做什么,但有两种可能性。
如果您不尝试替换 的全局值atolye
,只需使用不同的名称:
def atolye_detail(request, id):
my_atolye = get_object_or_404(atolye, id=id)
context = { 'atolye': my_atolye, }
return render(request, 'atolye_detail.html', context)
如果您试图替换 的全局值,则atolye
需要global
声明:
def atolye_detail(request, id):
global atolye
atolye = get_object_or_404(atolye, id=id)
context = { 'atolye': atolye, }
return render(request, 'atolye_detail.html', context)
推荐阅读
- java - 通过对其他 API 进行异步调用来提高 Spring Boot Web 服务的性能
- laravel - @click 显示 ReferenceError: 函数未使用 AlpineJS + Livewire + Laravel 定义
- python - 如何从多个数据框中添加或减去值
- python - Python:ValueError:Expecting,分隔符:加载json时的第1行
- html - 为什么变换:倾斜(30度);与变换不同:matrix(1,0,30,1,0,0);?
- typescript - TypeScript 定义,如何通过匹配参数中的某个值来对函数的参数进行不同的约束
- javascript - 只有一部分数据来自 https.request
- java - 如何告诉 MapperModel 的 map 函数,特定的字段应该具有特定的值?
- centos7 - OpenStack Train 找不到合适的 TLS CA 证书包
- reactjs - Firebase auth 和 React Hook - 从钩子返回的函数不起作用