Skip to content

Instantly share code, notes, and snippets.

@senko
Created November 26, 2011 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save senko/1395402 to your computer and use it in GitHub Desktop.
Save senko/1395402 to your computer and use it in GitHub Desktop.
Render a Django template passing all local variables to the RequestContext automatically.
import django.shortcuts
import inspect
def renderlocals(template):
"""
Renders the template in a RequestContext, passing all local
variables to the request context, and returns the resulting
HttpResponse.
Example usage:
def my_view(request):
foo = 42
return renderlocals('mytemplate.html')
"""
locals = inspect.stack()[1][0].f_locals
request = locals.get('request')
return django.shortcuts.render(request, template, locals)
@domenkozar
Copy link

Note that this works on CPython only :)

@senko
Copy link
Author

senko commented Nov 26, 2011

Thanks for the info. The (C)Python docs (http://docs.python.org/library/inspect.html) led me to believe only the currentframe() function is CPython-only. I haven't tested it with PyPy or other interpreters - I suppose there's a different but equivalent way of getting the parent stack frame there?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment