视图music.views.detail没有返回HttpResponse对象。它返回了None

时间:2017-07-19 17:55:49

标签: python django

我的VIEW.PY文件是:

from django.http import Http404
from django.shortcuts import render 
from .models import Album

def index(request):
all_albums = Album.objects.all()
return render(request, 'music/index.html', {'all_albums': all_albums})
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})'

DETAIL.HTML文件是:

{{ album }}

我收到错误:

  

视图music.views.detail没有返回HttpResponse对象。它返回None而不是

1 个答案:

答案 0 :(得分:1)

返回语句,使其位于except块之外。

try:
    album = Album.objects.get(pk=album_id)
except Album.DoesNotExist:
    raise Http404("Album does not exist")
return render(request, 'music/index.html', {'album': album})

请注意,您可以使用get_object_or_404快捷方式稍微简化视图:

from django.shortcuts import render, get_object_or_404

def detail(request, album_id):
    album = get_object_or_404(Album, pk=album_id)
    return render(request, 'music/index.html', {'album': album})'