Django View Decorators

Posted by Bryan in Web Development

Looking for a few shortcut Django view decorators?

Here are a few decorators I wrote this week to simply the view handling for redirects and JSON rendering. The source code is posted on djangosnippets.org.

Some example usage of the decorators:

@permanent_redirect('/another-view/')
def process_view(request, arg1, arg2):
    ...

@redirect(lambda: reverse('some_viewname'))
def do_redirect(request):
    ...

@render_to_json(indent=2)
def ajax_view(request):
    ...
    return dict(result=True)

These three python decorators will help you simply common view behavior. 

The redirect decorators are not a replacement for the existing Django redirect shortcuts. They are very similar in purpose, but are a different way to attach the redirect.

The JSON decorator leaves the error handling out to keep things simple. If you have a common way of returning the error state to the frontend, modify the json decorator to suite your needs.