【问题标题】:Put a Rendered Django Template in Json along with some other items将渲染的 Django 模板与其他一些项目一起放入 Json
【发布时间】:2016-03-31 07:12:12
【问题描述】:

假设有一个视图,它有一个链接到它的模板,并且视图传递了一些上下文日期,即对象到模板,模板渲染它,我在浏览器中得到一个渲染的 html,只是典型的视图,

# views.py

def view_name(request, params):
    objects = Object.objects.all()
    somevar = "something"
    request_id = 123456

    # Context to be passed on to template
    context = {'objects':objects}

    return render(request, 'appname/template.html', context)

但我不只是想要呈现的 html,我希望JSON 的输出格式如下

{"somevar":"something","html":"rendered html coming from template.html ","request_id":"123456"}

如果将视图调用为 AJAX,我可以轻松区分 html 和其他值

如果我能说得更清楚,请提出任何问题!

【问题讨论】:

    标签: javascript python json ajax django


    【解决方案1】:

    使用render_to_string() 快捷方式和JsonResponse

    from django.http import JsonResponse
    from django.template.loader import render_to_string
    
    
    def view_name(request, params):
        objects = Object.objects.all()
        somevar = "something"
        request_id = 123456
    
        # Context to be passed on to template
        context = {'objects':objects}
    
        rendered_html = render_to_string('appname/template.html', context)
    
        return JsonResponse({
            "somevar": somevar,
            "html": rendered_html,
            "request_id": request_id
        })
    

    【讨论】:

    • 我如何导入我的意思是从哪个类或模块render_to_string()
    • @HassanNaseer 导入语句也在答案中,检查一下。
    • 不知道为什么我会收到'WSGIRequest' object has no attribute 'push'
    • 刚刚导入render_to_string
    • 在文档中它说我可以将请求对象传递给这个函数,但是当我这样做时,我得到那个请求错误提到我需要模板中的那个请求对象来做像request.user 这样的事情
    猜你喜欢
    • 1970-01-01
    • 2015-10-26
    • 2018-05-22
    • 1970-01-01
    • 2017-08-06
    • 2015-04-22
    • 1970-01-01
    • 2022-07-22
    • 1970-01-01
    相关资源
    最近更新 更多