【问题标题】:render_to_string gives error whereas render worksrender_to_string 给出错误,而渲染工作
【发布时间】:2019-08-07 05:53:35
【问题描述】:

我正在尝试将响应返回给 Ajaz 请求。在 python 代码中可以看到该视图,但如果我尝试使用 render_to_string 将响应呈现给字符串,则会收到一条错误消息:

django.template.exceptions.TemplateDoesNotExist:

如果我使用相同的参数运行渲染方法,则不会出现错误。每个代码如下所示:

    html = render_to_string(request, 'planner/viewconnections.html', { 'routes' : routelist })
    render(request, 'planner/viewconnections.html', { 'routes' : routelist })

显然第一个是我想要运行的,因此我可以将原始 html 返回到 AJAX 成功函数。

我在 settings.py 中的模板配置如下:

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},

]

我已经尝试如下添加模板目录,但我仍然得到同样的错误。

ROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname((__file__)),".."))

   # Other settings...
   TEMPLATE_DIRS = (
    os.path.join(PROJECT_ROOT, "planner/templates"),
)

有人可以帮忙吗?我对这个问题的搜索让我在设置中添加了 TEMPLATE_DIRS,但这没有用。我不明白为什么一种渲染方法可以提取模板,而另一种则不能。

【问题讨论】:

标签: python ajax django django-templates


【解决方案1】:

在 django 中的 render_to_string request 参数不是必需的

语法

render_to_string(template_name, context=None, request=None, using=None)



 html = render_to_string('planner/viewconnections.html', { 'routes' : routelist })

参考这个https://docs.djangoproject.com/en/2.1/topics/templates/#django.template.loader.render_to_string

【讨论】:

    猜你喜欢
    • 2015-09-03
    • 2017-11-12
    • 2011-10-28
    • 2014-10-22
    • 2014-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-22
    相关资源
    最近更新 更多