PageRenderTime 44ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/django/shortcuts/__init__.py

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