我在views.py文件中出现错误,因此我无法加载页面。
音乐/ views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Album
# Create your views here.
#each URL is connected to a view or an Http Response
def index(request):
all_albums = Album.objects.all()
html = ' '
for album in all_albums:
url= '/music/' + str(album_id) + '/'
html +='<a href="' + url + '">'+album.album_title+'</a><br>'
return HttpResponse(html)
def detail(request,album_id):
return HttpResponse("<h2>Details for Album id:" + str(album_id) + "</h2>")
导致错误的行大概是:
url= '/music/' + str(album_id) + '/'
实际(页面)错误是:
NameError at /music/
name 'album_id' is not defined
Request Method: GET
Request URL: http://127.0.0.1:8000/music/
Django Version: 2.0
Exception Type: NameError
Exception Value:
name 'album_id' is not defined
Exception Location: C:\Users\User\Desktop\website\music\views.py in index, line 13
Python Executable: C:\Python34\python.exe
Python Version: 3.4.3
Python Path:
['C:\\Users\\User\\Desktop\\website',
在一个单独的测试中,album_id确实似乎是“可访问的”
http://127.0.0.1:8000/music/1/
将正确加载页面(相册ID号显示在页面上)。
错误指向上面的代码,但我看不到如何解决它。继新波士顿教程之后,我用谷歌搜索是否有一个Django 2.0修复无济于事
总结一下:
http://127.0.0.1:8000/music/是不起作用的。
http://127.0.0.1:8000/music/1或http://127.0.0.1:8000/music/3显示正常生成的专辑ID。
UPDATE
还发布了urls.py
from django.contrib import admin
from django.urls import include, path
from . import views #the dot means look at the current directory - look for a module called views
urlpatterns = [
#this is matching /music/
path('', views.index, name='index'),
path("<album_id>/", views.detail, name="detail")
]
def index(request):
all_albums = Album.objects.all()
html = ' '
for album in all_albums:
url= '/music/' + str(album_id) + '/'
在使用之前,您尚未定义album_id
。
你在循环for album in all_albums:
,所以如果你想要专辑ID,请使用album.id
。
你通常不会在视图中构建字符串。希望您的教程将在以后继续渲染模板。