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>"); } });
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With