Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I send empty response in Django without templates

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>");         }     }); 
like image 833
Srikar Appalaraju Avatar asked Nov 08 '10 10:11

Srikar Appalaraju


People also ask

How do I return an empty response in Django?

If you're getting empty responses and not errors, then your view code is being executed and the empty response is coming from your code. Add some logging to your views (prints to stderr will appear in your error log) so you can see if it's taking an unexpected code path that ends up returning empty responses.

Can you use Django without templates?

Is it possible to render HTML using Django if you are not using a templating system? Yes, it is possible to do this. In order to render HTML without a template in Django, we'll need to manually build up a string of HTML and send that to the browser as an HttpResponse.


1 Answers

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.

like image 191
Daniel Roseman Avatar answered Oct 13 '22 11:10

Daniel Roseman