【问题标题】:Django include template using JavascriptDjango包含使用Javascript的模板
【发布时间】:2025-12-04 20:10:02
【问题描述】:

我来自 Rails 背景,因此这个问题可能看起来很愚蠢。 在 Rails 中,当我们创建 Ajax 请求时,我们可以通过使用 javascript 选择器渲染部分视图来更新视图,如下所示:

$("#dashboardEmails").html("<%=j render partial: 'emails', locals: {emails: @emails} %>");

如何在 Django 模板中做到这一点?我尝试了以下方法:

$.ajax({
        type: frm.attr('method'),
        url: frm.attr('action'),
        data: frm.serialize() + "&submit=connect",
        success: function (data) {
          if(data['tables'].length > 0){
            $('#data-connection-info').html("{% include 'projects/connection_info.html' with data='"data"' %}");
          }
          console.log(data);
        },
        error: function (data) {
          console.log("Error");
        }
});

在这里,我想使用模板projects/connection_info.html 更新视图,同时使用with 将javascript 变量(data) 传递给模板。但它不起作用。

知道如何实现吗?

更新

我从视图中传递了模板,例如:

template = render_to_string('projects/connection_info.html', json_data)
return HttpResponse(json.dumps(template), content_type='application/json')

然后在ajax成功函数中更新DOM:

success: function (data) {
          $('#data-connection-info').html(data);
 }

这样问题就解决了。 :)

【问题讨论】:

  • 你不能这样做,但你可以从你的 django 视图返回完整呈现的 html 或空字符串,并始终在 DOM 中设置结果。
  • @BearBrown 有关您的解决方案的任何示例?
  • 将模板的html保存在一个变量中。 var connection_info_html ={% include 'projects/connection_info.html' %} ajax 成功更改后,使用该变量更新 DOM 。 Django 的 include、extends 等是在服务器上处理的,所以一旦 html 被渲染,你就不能使用它了。
  • 您可以做的一件事是使用 render_to_string 并在视图中返回 JsonResponse。然后,您可以通过 .html 之类的方法使用 javascript 将结果插入页面
  • @DisneylandSC 我用render_to_stringHttpResponse 传递了模板。现在.html 更新了 dom 元素,但是通过模板传递的数据无法访问到传递的模板中。

标签: javascript ajax django python-3.x django-templates


【解决方案1】:

我从视图中传递了模板,例如:

template = render_to_string('projects/connection_info.html', json_data)
return HttpResponse(json.dumps(template), content_type='application/json')

然后在ajax成功函数中更新DOM:

success: function (data) {
          $('#data-connection-info').html(data);
 }

这样问题就解决了。 :)

【讨论】:

  • 为什么json.dumps()渲染的模板???普通的 html 响应也可以。