浏览到 localhost:8000/x 时 /x/ 处的 Django UnboundLocalError

Django UnboundLocalError at /x/ when surfing to localhost:8000/x

我是 Django 的新手,我刚刚用几个 类 创建了一个模型,并创建了视图和 urls,一切正常,直到我尝试提取对象的 ID在 url 中使用它。这是我的代码:

urls.py:

from django.conf.urls import url
from . import views

urlpatterns = [
    # / structures/
    url(r'^$', views.index, name='index'),

    # / structures/712
    url(r'^(?P<structure_id>[0-9]+)/$', views.detail, name='detail'),
]

views.py:

from django.http import HttpResponse
from .models import Structure

def index(request):
    all_structures = Structure.objects.all()
    html = ''
    for Structure in all_structures:
        url = '/structures/' + str(Structure.id) + '/'
        html += '<a href="' + url + '">' + Structure.name + '</a><br>'
    return HttpResponse(html)

def detail(request, structure_id):
    return HttpResponse("<h2>Details for Structure id " + str(structure_id) + "</h2>")

models.py:

from django.db import models

class Structure(models.Model):
    name = models.CharField(max_length=120)
    path = models.CharField(max_length=200)

    def __str__(self):
        return self.name

class Type(models.Model):
    typename = models.CharField(max_length=50)

    def __str__(self):
        return self.typename

class Record(models.Model):
    structure = models.ForeignKey(Structure, on_delete=models.CASCADE) #each structure has many records, each per line
    name = models.CharField(max_length=200)
    type = models.ForeignKey(Type)
    pos = models.IntegerField()
    long = models.IntegerField()

    def __str__(self):
        return self.name

这是我遇到的错误:

我的代码没有发现任何错误的引用或任何问题。我也在看 "thenewboston" 教程,我正在执行与 Bucky 完全相同的步骤。这对他来说很好,但对我来说不是。

谢谢你帮助我!

您正在使用 class 名称 Structure 作为 forloop 的变量。使用 structure.