zzbil
zzbil

Reputation: 357

Django return render template and Json response

How could i render template in Django and as well make a JsonResponse in one return?

return render(request, 'exam_partial_comment.html', {'comments': comments, 'exam_id': exam})

Im trying to compine this with JsonResponse or something like this so it would render exam_partial_comment.html and also return

JsonResponse({"message": message})

so I could display message with ajax success funtction:

console.log(data.message)

Upvotes: 0

Views: 5101

Answers (1)

kartikmaji
kartikmaji

Reputation: 966

Well as mentioned by @nik_m. You cannot send both html and json in your response. Plus, given the fact, Ajax calls cant render templates. Though, you can do something like this to achieve what you want

In views.py

def view_name(request):
    if request.method == 'POST':
        html = '<div>Hello World</div>'
        return JsonResponse({"data": html, "message": "your message"})

In html

<div id="test"></div>
<script>
$(document).ready(function(){
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: '/view/',
        data: data,
        success: function(response) {
             console.log(response.message);
             $('#test').append(response.data);
       }
    });
});
</script>

Hope this helps.

Upvotes: 1

Related Questions