我在 django python 中遇到这个错误:
“/myapp/处出现 UnboundLocalError” 赋值前引用的局部变量“album”
我在 models.py 文件中创建了一个类并在 View 中导入,但遇到了此错误
这是两个文件的完整代码:
模型.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)
最佳答案
在循环内移动标题并更好地使用循环变量名称,而不是像模型
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)
关于python - 我在 django 中不断收到以下错误 : "UnboundLocalError at/myapp/",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45320036/