How do I send empty response in Django without templates

PythonAjaxDjangoDjango Views

Python Problem Overview


I have written a view which responds to ajax requests from browser. It's written like so -

@login_required
def no_response(request):
    params = request.has_key("params")
    if params:
        # do processing
        var = RequestContext(request, {vars})
        return render_to_response('some_template.html', var)
    else: #some error
        # I want to send an empty string so that the 
        # client-side javascript can display some error string. 
        return render_to_response("") #this throws an error without a template.

How do i do it?

Here's how I handle the server response on client-side -

    $.ajax
    ({
        type     : "GET",
        url      : url_sr,
        dataType : "html",
        cache    : false,
        success  : function(response)
        {
            if(response)
                $("#resp").html(response);
            else
                $("#resp").html("<div id='no'>No data</div>");
        }
    });

Python Solutions


Solution 1 - Python

render_to_response is a shortcut specifically for rendering a template. If you don't want to do that, just return an empty HttpResponse:

 from django.http import HttpResponse
 return HttpResponse('')

However, in this circumstance I wouldn't do that - you're signalling to the AJAX that there was an error, so you should return an error response, possibly code 400 - which you can do by using HttpResponseBadRequest instead.

Solution 2 - Python

I think the best code to return an empty response is 204 No Content.

from django.http import HttpResponse
return HttpResponse(status=204)

However, in your case, you should not return an empty response, since 204 means: The server *successfully* processed the request and is not returning any content..

It is better returning some 4xx status code to better signal the error is in the client side. Yo can put any string in the body of the 4xx response, but I highly recommend you send a JSONResponse:

from django.http import JsonResponse
return JsonResponse({'error':'something bad'},status=400)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSrikar AppalarajuView Question on Stackoverflow
Solution 1 - PythonDaniel RosemanView Answer on Stackoverflow
Solution 2 - PythonrobermoralesView Answer on Stackoverflow