【问题标题】:How I can change render to return json in view Django [duplicate]如何在视图 Django 中更改渲染以返回 json [重复]
【发布时间】:2018-04-27 13:17:24
【问题描述】:

我正在查看函数

from django.shortcuts import render
from .models import myModel

def articleTheme(request):
    if request.method == 'POST':
        article_id = request.POST['id']
        article = myModel.objects.get(id=article_id)
        theme = article.theme
        return render(request, 'theme.html', {'newTheme': theme })

现在它可以正常工作了。但是我有多余的html。我想返回 json 对象。 我可以导入和返回什么?

【问题讨论】:

    标签: python django


    【解决方案1】:

    使用JsonResponse

    from django.http import JsonResponse
    ..
    def articleTheme(request):
        ..
        return JsonResponse({'newTheme': theme })
    

    【讨论】:

    • 然后如何在下一个视图函数中访问这个?。
    • 模板如何加载??
    【解决方案2】:

    您可以使用HttpResponse 和 JSON 格式返回数据,如下所示:

    data = {'newTheme': theme}
    data = json.dumps(data, cls=DjangoJSONEncoder)
    return HttpResponse(data)
    

    【讨论】:

      猜你喜欢
      • 2013-05-11
      • 2014-03-16
      • 2015-10-02
      • 2018-05-17
      • 2019-09-04
      • 2018-06-16
      • 2021-12-25
      • 2011-09-05
      • 1970-01-01
      相关资源
      最近更新 更多