1

我尝试将多个值发送到渲染字典方法,但我只能达到模板中的第一个值。

我的views.py代码:

from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.views import generic

from books.models import Book
from places.models import Symbol

class IntroView(generic.DetailView):
    model = Book
    template_name = 'books/intro.html'

def intro(request, book_id):
    book = get_object_or_404(Book, pk=book_id)
    symbol_list = Symbol.objects.all().order_by('name')
    return render(request, 'books/intro.html', {'book': book, 'symbol_list': symbol_list})

和我的 intro.html 模板:

{% extends "base.html" %}
{% block content %}

<h2>{{ book.name }}</h2>
<h3>{{ book.catch_line }}</h3>
<em>{{ book.publication_year }}</em>

<hr />

<h4>Symbols</h4>
{% if symbol_list %}
    <ul>
    {% for symbol in symbol_list %}
        <li><img src="{{ symbol.icon.url }}"/>{{ symbol.name }}</li>
    {% endfor %}
    </ul>
{% else %}
    <p>No symbols yet...</p>
{% endif %}

{% endblock %}

在模板symbol_list中始终为空,但模型有一些值。

[编辑]我的 urls.py 文件:

from django.conf.urls import patterns, url

from books import views

urlpatterns = patterns('',
    url(r'^(?P<pk>\d+)/$', views.IntroView.as_view(), name='intro'),
)
4

1 回答 1

0

正如您所确定的,您正在使用基于类的视图IntroView,您没有传入该视图。symbol_list

尝试如下修改您的视图:

class IntroView(generic.DetailView):
    model = Book
    template_name = 'books/intro.html'

    def get_context_data(self, **kwargs):
        context = super(IntroView, self).get_context_data(**kwargs)
        context['symbol_list'] = Symbol.objects.all().order_by('name')
        return context
于 2013-07-19T10:26:51.917 回答