【发布时间】:2017-07-26 07:19:08
【问题描述】:
我在 django python 中遇到了这个错误:
“/myapp/ 处的 UnboundLocalError” 赋值前引用的局部变量“专辑”
我在 models.py 文件中创建了一个类并在视图中导入但遇到此错误
这是两个文件的完整代码:
Models.py
from django.db import models
from django.db import models
class album(models.Model):
artist = models.CharField(max_length=250)
title = models.CharField(max_length=500)
gender = models.CharField(max_length=100)
def __str__(self):
return self.artist+'--'+self.title
views.py
from django.http import HttpResponse
from .models import album
def myapp(request):
all_albums = album.objects.all()
title = album.artist
html = ''
for album in all_albums:
url = '/myapp/' + str(album.id) + '/'
html += '<a href="' + url + '">' + title + '</a><br>'
return HttpResponse(html)
【问题讨论】:
-
您正在多次使用
album变量。一次作为模型,其他时间作为实例。理想情况下,模型名称应该是 CamelCased。 -
你能解释一下如何用 CamelCased 编写模型代码吗?
-
您只需将
class album(models.Model):更改为class Album(models.Model):,如my answer 中所述。但这并不能解决问题。
标签: python django local-variables