Commits

Jakub Zalewski committed 16939ec

render_to_list decorator (returns object_list)

Comments (0)

Files changed (1)

annoying/decorators.py

-from django.shortcuts import render_to_response
 from django import forms
-from django.template import RequestContext
+from django.contrib.sites.models import Site
+from django.core.exceptions import PermissionDenied
 from django.db.models import signals as signalmodule
 from django.http import HttpResponse
+from django.shortcuts import render_to_response
+from django.template import RequestContext
 from django.utils import simplejson
-from django.core.exceptions import PermissionDenied
+from django.views.generic.list_detail import object_list
 
 __all__ = ['render_to', 'signals', 'ajax_request', 'autostrip']
 
 
 try:
     from functools import wraps
-except ImportError: 
+except ImportError:
     def wraps(wrapped, assigned=('__module__', '__name__', '__doc__'),
               updated=('__dict__',)):
         def inner(wrapper):
 
 def render_to(template=None, mimetype="text/html"):
     """
-    Decorator for Django views that sends returned dict to render_to_response 
+    Decorator for Django views that sends returned dict to render_to_response
     function.
 
-    Template name can be decorator parameter or TEMPLATE item in returned 
+    Template name can be decorator parameter or TEMPLATE item in returned
     dictionary.  RequestContext always added as context instance.
     If view doesn't return dict then decorator simply returns output.
 
 
     @render_to('template.html')
     def foo(request):
-        bar = Bar.object.all()  
+        bar = Bar.object.all()
         return {'bar': bar}
 
-    # equals to 
+    # equals to
     def foo(request):
-        bar = Bar.object.all()  
-        return render_to_response('template.html', 
-                                  {'bar': bar}, 
+        bar = Bar.object.all()
+        return render_to_response('template.html',
+                                  {'bar': bar},
                                   context_instance=RequestContext(request))
 
 
     # 2. Template name as TEMPLATE item value in return dictionary.
-         if TEMPLATE is given then its value will have higher priority 
+         if TEMPLATE is given then its value will have higher priority
          than render_to argument.
 
     @render_to()
     def foo(request, category):
         template_name = '%s.html' % category
         return {'bar': bar, 'TEMPLATE': template_name}
-    
+
     #equals to
     def foo(request, category):
         template_name = '%s.html' % category
-        return render_to_response(template_name, 
-                                  {'bar': bar}, 
+        return render_to_response(template_name,
+                                  {'bar': bar},
                                   context_instance=RequestContext(request))
 
     """
     return renderer
 
 
+def render_to_list(template=None, mimetype="text/html"):
+    """
+    Decorator for Django views that sends returned dict to object_list
+    function.
+
+    Example:
+
+    @render_to_list('myapp/index.html')
+    def index(request):
+        items = Baz.objects.all()
+        foo = 'hello'
+        return {'queryset': items, 'paginate_by': 10,
+            'extra_context': {'foo': foo, }, }
+    """
+
+    def renderer(function):
+        @wraps(function)
+        def wrapper(request, *args, **kwargs):
+            output = function(request, *args, **kwargs)
+            if not isinstance(output, dict):
+                return output
+            tmpl = output.pop('TEMPLATE', template)
+            return object_list(request, template_name=tmpl, **output)
+
+        return wrapper
+    return renderer
+
 
 class Signals(object):
     '''
        # connect to any signal
        signals.register_signal(siginstance, signame) # and then as in example above
 
-       or 
-        
+       or
+
        @signals(siginstance, sender=YourModel)
        def sighandler(instance, **kwargs):
            pass
 signals = Signals()
 
 
-
 class JsonResponse(HttpResponse):
     """
     HttpResponse descendant, which return response with ``application/json`` mimetype.
         super(JsonResponse, self).__init__(content=simplejson.dumps(data), mimetype='application/json')
 
 
-
 def ajax_request(func):
     """
     If view returned serializable dict, returns JsonResponse with this dict as content.
 
     example:
-        
+
         @ajax_request
         def my_view(request):
             news = News.objects.all()
         email = forms.EmailField()
 
     PersonForm = autostrip(PersonForm)
-    
+
     #or you can use @autostrip in python >= 2.6
 
     Author: nail.xx
                 return view_func(request, *args, **kwargs)
             raise PermissionDenied()
         _check_referer.__doc__ = view_func.__doc__
-        _check_referer.__dict__ = view_func.__dict__        
+        _check_referer.__dict__ = view_func.__dict__
         return _check_referer
     return _dec
 
                 return view_func(request, *args, **kwargs)
             raise PermissionDenied()
         _check_referer.__doc__ = view_func.__doc__
-        _check_referer.__dict__ = view_func.__dict__        
+        _check_referer.__dict__ = view_func.__dict__
         return _check_referer
     return _dec
 
-from django.contrib.sites.models import Site
 local_referer_only = referer_matches_hostname(str(Site.objects.get_current()))
 ## Same, but using referer_matches_re:
 # regex = r'^https?://%s/.*' % Site.objects.get_current()
     Decorator for views that checks that if the request's HTTP_REFERER matches
     the current site. If not, a PermissionDenied exception is raised.
     """
-)
+)