我是Django的新手,我刚创建了一个包含很少类的模型,并创建了视图和网址,一切正常,直到我尝试提取对象的id以在网址中使用它。这是我的代码:
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完全相同的步骤。它对他来说很好,但不是我。
感谢帮助我!
答案 0 :(得分:4)
您使用类名Structure
作为forloop的变量。使用structure
。