首页 > 解决方案 > 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。

标签: pythondjangodjango-1.10

解决方案


我在这里进行了一些猜测,因为您的异常回溯与您的标题或描述都不匹配,并且您的代码不可读,但是……</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)

推荐阅读