首页 > 解决方案 > Django - 如何渲染 html 并同时返回一个 json

问题描述

我有一个填充 json 对象的视图,然后,在同一视图的末尾,我将呈现一个 html 页面,但也返回最终的 json。

可能这无关紧要,但 json 可能是这样的:

{
    "embedToken": "dasfgjasdàgjasdàgasdàgèe-AveryLongToken",
    "embedUrl": "https://app.powerbi.com/let's_go_to_the_lake",
    "reportId": "e615-sfash-9746"
}

我无法修复的行(用所有替代方法尝试了一整天)如下:

return render(request, "home.html", jsn)

我的 url.py 很简单,如下所示:

urlpatterns = [
    path('', HomePageView, name='home'),
]

我目前收到以下错误:

context must be a dict rather than str.

但是我在途中遇到了各种不同类型的错误,但没有成功达到预期的结果(渲染 html 并同时返回 json)。所以我怀疑我在基础上采取了错误的方法,我应该改变道路吗?

我想尝试将 json 转换为字典,然后在 javascript 中将其转换回 json

我还尝试通过将 html 呈现为 django 视图并从 javascript ajax 请求执行函数调用来拆分我的请求,如下所示:

function handler1(){
    // there are many other methods like $.get $.getJSON
    $.ajax({
       type: 'GET',
       dataType: 'json',
       url: "http://piedpiper.com/api/callers"
    }).then(function(result) {
        // do something with the result

    });
}

但我最终了解到,通过这种方式,我必须创建 URL api/callers,每个人都可以使用/可访问,但由于用户会话,我无法做到这一点。只有登录的用户才能看到 json 数据

标签: jsondjangoviewrendering

解决方案


您需要在渲染上添加正确的参数。这是 Django 中渲染函数的文档

这是一个视图的示例代码

def post_detail(request, slug=None):
    instance = get_object_or_404(Post, slug=slug)
    share_string = quote_plus(instance.content)
    context = {
        "title": instance.title,
        "instance": instance,
        "share_string": share_string,
    }
    return render(request, "post_detail.html", context)

推荐阅读