shortcuts.py 5.6 KB

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