如何在视图Django中更改渲染以返回json

Sur*_*a94 3 python django

我有功能在视野中

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 })
Run Code Online (Sandbox Code Playgroud)

现在它正常工作.但我有多余的HTML.我想要返回json对象.我可以导入和返回什么?

Abh*_*kan 8

使用 JsonResponse

from django.http import JsonResponse
..
def articleTheme(request):
    ..
    return JsonResponse({'newTheme': theme })
Run Code Online (Sandbox Code Playgroud)