Django中这个模板有什么问题?

时间:2017-06-17 11:59:37

标签: python django

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错误。 而代码是 -

    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/时,它会开始在/ music / 2 /中出现“TemplateDoesNotExist”错误。 为什么会发生这种情况......

1 个答案:

答案 0 :(得分:0)

问题是您的模板文件details.html应该是detail.htmls之后不应该detail,就像views.py一样,它被称为{ {1}}。

您可以在music/detail.html中更改为music/details.html

模板名称应匹配。