[Fixed]-Django return render template and Json response

1👍

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.

Leave a comment