2

我有一个具有以下模型的 Django 应用程序:

class Topic(models.Model):
    title = models.CharField(max_length=140)

有一个 URL,应该显示Topic的详细信息:

urlpatterns = patterns('',
    [...]
    (r'^topic/(\d+)$', 'history_site.views.topic_details'),
    [...]
)

history_site.views.topic_details定义为

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template.loader import get_template
from django.template import Context, RequestContext
from django.views.decorators.csrf import csrf_protect
import logging
from opinions.models import Topic
from django.template.response import TemplateResponse

logging.basicConfig(filename='history-site.log',level=logging.DEBUG)

def topic_details(request, topic_id_string):
    topic_id = int(topic_id_string)
    topic = Topic.objects.get(id=topic_id)
    return TemplateResponse('topic.tpl.html', locals())

topic.tpl.html有以下内容:

<!DOCTYPE html>

{% block prehtml %}
{% endblock %}

<html>
<head>
    <title>{% block title %}{% endblock %}</title>
    {% block scripts %}{% endblock %}
</head>
<body>
<h1>{{ topic.title }} </h1>


{% block content %}
{% endblock %}

</body>
</html>

当我尝试访问 URLhttp://127.0.0.1:8000/topic/1时出现错误'str' object has no attribute 'META'

为什么?

我该如何解决?

4

1 回答 1

4

看着文档

TemplateResponse.__init__(request, template, context=None, content_type=None, status=None, current_app=None)

TemplateResponse 采用的第一个参数是请求而不是模板名称

所以您的代码是错误的,请尝试将其更改为:

return TemplateResponse(request, 'topic.tpl.html', locals())
于 2013-06-20T19:56:34.363 回答