/django/shortcuts/__init__.py
Python | 130 lines | 129 code | 0 blank | 1 comment | 0 complexity | e8f71553823b8be8f7f07646cb315548 MD5 | raw file
1""" 2This module collects helper functions and classes that "span" multiple levels 3of MVC. In other words, these functions/classes introduce controlled coupling 4for convenience's sake. 5""" 6 7from django.template import loader, RequestContext 8from django.http import HttpResponse, Http404 9from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect 10from django.db.models.manager import Manager 11from django.db.models.query import QuerySet 12from django.core import urlresolvers 13 14def render_to_response(*args, **kwargs): 15 """ 16 Returns a HttpResponse whose content is filled with the result of calling 17 django.template.loader.render_to_string() with the passed arguments. 18 """ 19 httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)} 20 return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) 21 22def render(request, *args, **kwargs): 23 """ 24 Returns a HttpResponse whose content is filled with the result of calling 25 django.template.loader.render_to_string() with the passed arguments. 26 Uses a RequestContext by default. 27 """ 28 httpresponse_kwargs = { 29 'content_type': kwargs.pop('content_type', None), 30 'status': kwargs.pop('status', None), 31 } 32 33 if 'context_instance' in kwargs: 34 context_instance = kwargs.pop('context_instance') 35 if kwargs.get('current_app', None): 36 raise ValueError('If you provide a context_instance you must ' 37 'set its current_app before calling render()') 38 else: 39 current_app = kwargs.pop('current_app', None) 40 context_instance = RequestContext(request, current_app=current_app) 41 42 kwargs['context_instance'] = context_instance 43 44 return HttpResponse(loader.render_to_string(*args, **kwargs), 45 **httpresponse_kwargs) 46 47def redirect(to, *args, **kwargs): 48 """ 49 Returns an HttpResponseRedirect to the apropriate URL for the arguments 50 passed. 51 52 The arguments could be: 53 54 * A model: the model's `get_absolute_url()` function will be called. 55 56 * A view name, possibly with arguments: `urlresolvers.reverse()` will 57 be used to reverse-resolve the name. 58 59 * A URL, which will be used as-is for the redirect location. 60 61 By default issues a temporary redirect; pass permanent=True to issue a 62 permanent redirect 63 """ 64 if kwargs.pop('permanent', False): 65 redirect_class = HttpResponsePermanentRedirect 66 else: 67 redirect_class = HttpResponseRedirect 68 69 # If it's a model, use get_absolute_url() 70 if hasattr(to, 'get_absolute_url'): 71 return redirect_class(to.get_absolute_url()) 72 73 # Next try a reverse URL resolution. 74 try: 75 return redirect_class(urlresolvers.reverse(to, args=args, kwargs=kwargs)) 76 except urlresolvers.NoReverseMatch: 77 # If this is a callable, re-raise. 78 if callable(to): 79 raise 80 # If this doesn't "feel" like a URL, re-raise. 81 if '/' not in to and '.' not in to: 82 raise 83 84 # Finally, fall back and assume it's a URL 85 return redirect_class(to) 86 87def _get_queryset(klass): 88 """ 89 Returns a QuerySet from a Model, Manager, or QuerySet. Created to make 90 get_object_or_404 and get_list_or_404 more DRY. 91 """ 92 if isinstance(klass, QuerySet): 93 return klass 94 elif isinstance(klass, Manager): 95 manager = klass 96 else: 97 manager = klass._default_manager 98 return manager.all() 99 100def get_object_or_404(klass, *args, **kwargs): 101 """ 102 Uses get() to return an object, or raises a Http404 exception if the object 103 does not exist. 104 105 klass may be a Model, Manager, or QuerySet object. All other passed 106 arguments and keyword arguments are used in the get() query. 107 108 Note: Like with get(), an MultipleObjectsReturned will be raised if more than one 109 object is found. 110 """ 111 queryset = _get_queryset(klass) 112 try: 113 return queryset.get(*args, **kwargs) 114 except queryset.model.DoesNotExist: 115 raise Http404('No %s matches the given query.' % queryset.model._meta.object_name) 116 117def get_list_or_404(klass, *args, **kwargs): 118 """ 119 Uses filter() to return a list of objects, or raise a Http404 exception if 120 the list is empty. 121 122 klass may be a Model, Manager, or QuerySet object. All other passed 123 arguments and keyword arguments are used in the filter() query. 124 """ 125 queryset = _get_queryset(klass) 126 obj_list = list(queryset.filter(*args, **kwargs)) 127 if not obj_list: 128 raise Http404('No %s matches the given query.' % queryset.model._meta.object_name) 129 return obj_list 130