如何修复“'str'对象没有属性'META'”错误?

时间:2013-06-20 19:44:23

标签: python django python-2.5

我有一个Django应用程序,其中包含以下模型:

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

有一个网址,应显示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>

当我尝试访问网址http://127.0.0.1:8000/topic/1时,收到错误'str' object has no attribute 'META'

为什么?

我该如何解决?

1 个答案:

答案 0 :(得分:4)

查看doc

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

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

所以你的代码是错误的,尝试改变它的类似:

return TemplateResponse(request, 'topic.tpl.html', locals())