我在django python中面临这个错误:
" / myapp /&#34的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)
答案 0 :(得分:2)
在循环内移动标题并更好地使用循环变量名称而不是模型
html = ''
for album_data in all_albums:
url = '/myapp/' + str(album_data.id) + '/'
title = album_data.artist
html += '<a href="' + url + '">' + title + '</a><br>'
return HttpResponse(html)
答案 1 :(得分:1)
像这样改变视图,
def myapp(request):
all_albums = album.objects.all()
html = ''
for album in all_albums:
url = '/myapp/' + str(album.id) + '/'
html += '<a href="' + url + '">' + album.artist + '</a><br>'
return HttpResponse(html)
答案 2 :(得分:0)
您使用album
名称作为多个变量,一次作为模型,其他时间作为实例。模型名称理想情况下应该是CamelCased。更正模型名称后,在title
循环内移动for
变量赋值。只做后者会解决你现在的问题,但是如果你坚持造型指南(PEP-8),你将来不会遇到这样的问题。
<强> models.py 强>
...
class Album(models.Model):
artist = models.CharField(max_length=250)
...
<强> views.py 强>
...
from .models import Album
def myapp(request):
all_albums = Album.objects.all()
html = ''
for album in all_albums:
title = album.artist
url = '/myapp/' + str(album.id) + '/'
html += '<a href="' + url + '">' + title + '</a><br>'
...
答案 3 :(得分:0)
完全复制并粘贴到您的视图中
from django.http import HttpResponse
from .models import album
def myapp(request):
all_albums = album.objects.all()
html = ''
for al in all_albums:
url = '/myapp/' + str(al.id) + '/'
html += '<a href="' + url + '">' + al.artist + '</a><br>'
return HttpResponse(html)