3

I have function in view

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 })

now it works normal. But I have excess html. I want return json object. What I can import and return?

Surina94
  • 93
  • 2
  • 5

2 Answers2

9

Use JsonResponse

from django.http import JsonResponse
..
def articleTheme(request):
    ..
    return JsonResponse({'newTheme': theme })
Abhijith Asokan
  • 1,865
  • 10
  • 14
0

You can return the data with HttpResponse and in JSON format like this:

data = {'newTheme': theme}
data = json.dumps(data, cls=DjangoJSONEncoder)
return HttpResponse(data)
K.Subrt
  • 26
  • 4