NinjaCipher:-*-:ro60

Django Render To Response Hack

I was working on perva.de and I needed to add a cookie to the response. Now thats not really a tough thing to do but it has one unfortunate side effect. Basically it makes you have to use the long handed method for rendering the template instead of being able to use the more concise render_to_response shortcut. Reason being that the render_to_response shortcut creates a HttpResponse object for you and when you create a cookie you already have a HttpResponse object thats holding your cookie. So I wrote this simple function that lets you pass in your own pre initialized HttpResponse object instead.

def render_response(*args, **kwargs):
        response = kwargs.pop('response', None)
        if response == None:
            from django.shortcuts import render_to_response
            return render_to_response(*args, **kwargs)
        else:
            from django.template import loader
            response.content = loader.render_to_string(*args, **kwargs)
            return response

You call it the same way as the normal render_to_response except it has an optional param that lets you pass in your pre initialized HttpResponse object.

return render_response('index.html',{'param1': 'param1value'},context_instance=RequestContext(request),response=my_response)

If you pass None as the first param the normal render_to_response is called. The context_instance and the params dict are both optional. You can read about how the normal render_to_response works here.

Now for the disclaimer…

I could be completely missing something simple that already allows you to do this but I didn’t see it. It seems like a very common prob and the folks at the Django project are sick python masters so it wouldn’t surprise me if they already though this through. So if that is the case please leave me a comment and/or call me names and enlighten me to the folly of my ways. I won’t hate you… much ;)

EDIT: I refactored the way the request arg was passed to make it more python like and cleaner. Now you pass it as a kwargs key val pair.

Del.icio.us Digg BlinkList Furl Ma.gnolia Reddit Spurl

One Response to “Django Render To Response Hack”

  1. rene Says:

    render_response() works well for me… Cheers!


    Rene

Leave a Reply

You must be logged in to post a comment.