Login

DRY template rendering decorator update

Author:
jakecr
Posted:
March 4, 2010
Language:
Python
Version:
1.1
Score:
-1 (after 3 ratings)

Based fully on snippet 1929

The update is: It checks to see the view returns an instance of HttpResponse and returns that rather than trying to render it. This allows you to return something like HttpResponseRedirect('/'), or use a normal render_to_response to use a different template.

Also updates cleandict as per comment on original snippet

In this case the 'render_template' decorator assumes there is a myview.html template. this keeps things simple and you DRY. Hope it helps.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#process a dict and remove by default the 'request' key
cleandict = lambda dlist, ignore = ['request'] : dict((key, val) for key, val in dlist.items() if key not in ignore)

from django.shortcuts import render_to_response
from django.http import HttpResponse

#render the template - assume a html format
def render_template(func):
    '''ensure the view using this has the template name matching it'''
    def render(*args, **kwargs):
        view_response = func(*args, **kwargs)
        if isinstance(view_response, HttpResponse):
            return view_response
        return render_to_response(func.__name__ + '.html', cleandict(view_response))
    return render

Example code:

@render_template
def myview(request):
   variables = {'Hello': 'World', 'Monty' : 'Python'}
   if request.POST:
      return HttpResponseRedirect('/somewhere/')
   return locals()

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

jakecr (on September 18, 2010):

Why the negative score? Please tell me if something is wrong with this!

#

Please login first before commenting.