【问题标题】:How to fix the "'str' object has no attribute 'META'" error?如何修复“'str'对象没有属性'META'”错误?
【发布时间】:2013-06-20 19:44:23
【问题描述】:

我有一个具有以下模型的 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>

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

为什么?

我该如何解决?

【问题讨论】:

  • 能否请您提供错误代码?
  • @VictorCastilloTorres 你可以在这里找到回溯 - dpaste.com/1257647
  • 我确实提出了一个必须解决你的问题的答案:D

标签: python django python-2.5


【解决方案1】:

看着doc

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    • 1970-01-01
    相关资源
    最近更新 更多