shortcuts.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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.http import (
  7. Http404, HttpResponse, HttpResponsePermanentRedirect, HttpResponseRedirect,
  8. )
  9. from django.template import loader
  10. from django.urls import NoReverseMatch, reverse
  11. from django.utils.functional import Promise
  12. def render(request, template_name, context=None, content_type=None, status=None, using=None):
  13. """
  14. Return a HttpResponse whose content is filled with the result of calling
  15. django.template.loader.render_to_string() with the passed arguments.
  16. """
  17. content = loader.render_to_string(template_name, context, request, using=using)
  18. return HttpResponse(content, content_type, status)
  19. def redirect(to, *args, permanent=False, **kwargs):
  20. """
  21. Return an HttpResponseRedirect to the appropriate URL for the arguments
  22. passed.
  23. The arguments could be:
  24. * A model: the model's `get_absolute_url()` function will be called.
  25. * A view name, possibly with arguments: `urls.reverse()` will be used
  26. to reverse-resolve the name.
  27. * A URL, which will be used as-is for the redirect location.
  28. Issues a temporary redirect by default; pass permanent=True to issue a
  29. permanent redirect.
  30. """
  31. redirect_class = HttpResponsePermanentRedirect if permanent else HttpResponseRedirect
  32. return redirect_class(resolve_url(to, *args, **kwargs))
  33. def _get_queryset(klass):
  34. """
  35. Return a QuerySet or a Manager.
  36. Duck typing in action: any class with a `get()` method (for
  37. get_object_or_404) or a `filter()` method (for get_list_or_404) might do
  38. the job.
  39. """
  40. # If it is a model class or anything else with ._default_manager
  41. if hasattr(klass, '_default_manager'):
  42. return klass._default_manager.all()
  43. return klass
  44. def get_object_or_404(klass, *args, **kwargs):
  45. """
  46. Use get() to return an object, or raise a Http404 exception if the object
  47. does not exist.
  48. klass may be a Model, Manager, or QuerySet object. All other passed
  49. arguments and keyword arguments are used in the get() query.
  50. Like with QuerySet.get(), MultipleObjectsReturned is raised if more than
  51. one object is found.
  52. """
  53. queryset = _get_queryset(klass)
  54. if not hasattr(queryset, 'get'):
  55. klass__name = klass.__name__ if isinstance(klass, type) else klass.__class__.__name__
  56. raise ValueError(
  57. "First argument to get_object_or_404() must be a Model, Manager, "
  58. "or QuerySet, not '%s'." % klass__name
  59. )
  60. try:
  61. return queryset.get(*args, **kwargs)
  62. except queryset.model.DoesNotExist:
  63. raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
  64. def get_list_or_404(klass, *args, **kwargs):
  65. """
  66. Use filter() to return a list of objects, or raise a Http404 exception if
  67. the list is empty.
  68. klass may be a Model, Manager, or QuerySet object. All other passed
  69. arguments and keyword arguments are used in the filter() query.
  70. """
  71. queryset = _get_queryset(klass)
  72. if not hasattr(queryset, 'filter'):
  73. klass__name = klass.__name__ if isinstance(klass, type) else klass.__class__.__name__
  74. raise ValueError(
  75. "First argument to get_list_or_404() must be a Model, Manager, or "
  76. "QuerySet, not '%s'." % klass__name
  77. )
  78. obj_list = list(queryset.filter(*args, **kwargs))
  79. if not obj_list:
  80. raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
  81. return obj_list
  82. def resolve_url(to, *args, **kwargs):
  83. """
  84. Return a URL appropriate for the arguments passed.
  85. The arguments could be:
  86. * A model: the model's `get_absolute_url()` function will be called.
  87. * A view name, possibly with arguments: `urls.reverse()` will be used
  88. to reverse-resolve the name.
  89. * A URL, which will be returned as-is.
  90. """
  91. # If it's a model, use get_absolute_url()
  92. if hasattr(to, 'get_absolute_url'):
  93. return to.get_absolute_url()
  94. if isinstance(to, Promise):
  95. # Expand the lazy instance, as it can cause issues when it is passed
  96. # further to some Python functions like urlparse.
  97. to = str(to)
  98. if isinstance(to, str):
  99. # Handle relative URLs
  100. if to.startswith(('./', '../')):
  101. return to
  102. # Next try a reverse URL resolution.
  103. try:
  104. return reverse(to, args=args, kwargs=kwargs)
  105. except NoReverseMatch:
  106. # If this is a callable, re-raise.
  107. if callable(to):
  108. raise
  109. # If this doesn't "feel" like a URL, re-raise.
  110. if '/' not in to and '.' not in to:
  111. raise
  112. # Finally, fall back and assume it's a URL
  113. return to