from django.shortcuts import render
from django.http import HttpResponse #http response sends back html/basic webpage
from django.conf.urls import include
from django.template import loader
from .models import Album
# Create your views here.
'''def index(request):
all_objects = Album.objects.all()
html = ''
for album in all_objects:
url = "/music/" + str(album.id) + "/"
html += '<a href = "' + url + '">' + album.album_title + '</a><br>'
return HttpResponse(html)
'''
def index(request):
all_albums = Album.objects.all()
#template = loader.get_template('music/index.html')
context = {'all_albums': all_albums}
return render(request, 'music/index.html', context)
#return HttpResponse(template.render(context, request))
def detail(request, album_id):
return HttpResponse("<h2>Details of Album with id:" + str(album_id)+ "</h2>")
產生完全正確的模板。 當我添加不存在的相冊模板。 這是我添加了2個相冊,並與我的數據庫同步,當我衝浪到第三個模板頁面時,我應該得到404錯誤。 而對於這個代碼是 -Django中的這個模板有什麼問題?
from django.http import Http404
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from .models import Album
def index(request):
all_albums = Album.objects.all()
#template = loader.get_template('music/index.html')
context = {'all_albums': all_albums}
return render(request, 'music/index.html', context)
#return HttpResponse(template.render(context, request))
#render has an inbuilt http return type
def detail(request, album_id):
try:
album = Album.objects.get(pk=album_id)
except Album.DoesNotExist:
raise Http404("Album does not exist")
return render(request, 'music/detail.html', {'album':album})
當我進入http://127.0.0.1:8000/music/3/它產生一個404錯誤,我想做的事,但是當我在http://127.0.0.1:8000/music/2/鍵入它開始給錯誤是「在/音樂/ 2/TemplateDoesNotExist」。 這究竟是爲什麼?
您似乎對什麼是模板和什麼是視圖感到困惑。您的原始代碼有效,因爲您沒有在詳細視圖中使用模板。您的第二個代碼引用了一個detail.html模板,該模板大概不存在。 –
不,我已經在index.html旁邊添加了一個detail.html模板... – shery224
它由{{album}} – shery224