simple_view

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template.context import RequestContext


def simple_view(template, mimetype='text/html'):
    '''
    Simplify views declararation.
    
    Usage:
    
    @simple_view('path/to/template.html')
    def view1(request):
        ...
        return {
            'context_var1': context_var1,
        }
    
    @simple_view('path/to/template.txt', mimetype='text/plain')
    def view2(request):
        pass # it's ok to return nothing     
    
    @simple_view('path/to/template.html')
    def view3(request):
        if some_condition:
            return redirect('view1') # You could return HttpResponse object
        return {}
    '''
    def decorator(func):
        def real_decorator(request, *args, **kwargs):
            returned = func(request, *args, **kwargs)
            if isinstance(returned, HttpResponse):
                return returned
            assert returned is None or isinstance(returned, dict)
            return render_to_response(template,
                                      returned or {},
                                      context_instance=RequestContext(request))
        return real_decorator
    return decorator

More like this

  1. view ModelForm by hrdcdr 1 year ago
  2. router view by tokibito 4 years, 3 months ago
  3. Register django views by magik_cypress 2 years, 2 months ago
  4. Generic Views for newforms by jnievas 6 years, 2 months ago
  5. clear cache view by zodman 1 year, 4 months ago

Comments

troolee (on July 1, 2010):

@buriy yep, with a little modification - view is able to return HttpResponse except of dict

#

troolee (on July 1, 2010):

@buriy it's pretty useful when you want to make redirection inside of the view

#

(Forgotten your password?)