无法使用模板将数据从模型传输到html

时间:2017-09-22 20:17:57

标签: django django-templates django-views

View.py

from django.shortcuts import render
from django.http import HttpResponse
from .models import Albums
from django.template import loader

def index(request):
    all_albums = Albums.objects.all()

    template = loader.get_template('Ganaana/index.html')
    context = {
        'all_albums':all_albums,
        }
    return HttpResponse(template.render(context,request))

def define(request,Albums_id):
    return HttpResponse("<h1>Your Id is "+str(Albums_id)+"</h1>");

的index.html

<html>
  <ul>  
    <% for albums in all_albums %>  
       <li><a href="/music/{{albums.id}}/">{{albums.artist}}</a></li>  
    <% endfor %>  
  </ul>  
</html>  

代码输出:

  <% for albums in all_albums %>
     albums.artist
  <% endfor %>

我不知道我使用模板文件夹的错误是什么,并将数据放入其中我不明白我正确导入类的问题..我不明白?

1 个答案:

答案 0 :(得分:1)

请使用:

from django.shortcuts import render

def index(request):
    return render(request, "Ganaana/index.html", {"all_albums": Albums.objects.all()})