python - 我在 django 中不断收到以下错误 : "UnboundLocalError at/myapp/"

标签 python django local-variables

我在 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/

相关文章:

python - 由于 bs4 vs BeautifulSoup 导致导入错误

python - 向文章 django createviewforeignkey 添加评论

python - 用django自己加入postgresql

c++ - 传递的局部变量 (C++)

c# - 使用集合初始值设定项时,另一个线程能否看到部分创建的集合?

python - 过滤列表,只有唯一值 - 使用 python

python - Bokeh 调整大小 - 绘制阴影小部件

python - 如何在Python中获取类路径

c++ - 多态局部变量的逼近

python - 值错误 : The model is not configured to compute accuracy