mirror of
https://github.com/django/django.git
synced 2025-11-23 12:26:57 +00:00
Fixed #10194: added django.shortcuts.redirect, a do-what-I-mean redirect shortcut. See the docs at topics/http/shortcuts for details.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10108 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
parent
4eadcf45d4
commit
d7e8127524
3 changed files with 160 additions and 15 deletions
|
|
@ -6,8 +6,10 @@ for convenience's sake.
|
|||
|
||||
from django.template import loader
|
||||
from django.http import HttpResponse, Http404
|
||||
from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect
|
||||
from django.db.models.manager import Manager
|
||||
from django.db.models.query import QuerySet
|
||||
from django.core import urlresolvers
|
||||
|
||||
def render_to_response(*args, **kwargs):
|
||||
"""
|
||||
|
|
@ -17,6 +19,43 @@ def render_to_response(*args, **kwargs):
|
|||
httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)}
|
||||
return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
|
||||
|
||||
def redirect(to, *args, **kwargs):
|
||||
"""
|
||||
Returns an HttpResponseRedirect to the apropriate URL for the arguments
|
||||
passed.
|
||||
|
||||
The arguments could be:
|
||||
|
||||
* A model: the model's `get_absolute_url()` function will be called.
|
||||
|
||||
* A view name, possibly with arguments: `urlresolvers.reverse()` will
|
||||
be used to reverse-resolve the name.
|
||||
|
||||
* A URL, which will be used as-is for the redirect location.
|
||||
|
||||
By default issues a temporary redirect; pass permanent=True to issue a
|
||||
permanent redirect
|
||||
"""
|
||||
if kwargs.pop('permanent', False):
|
||||
redirect_class = HttpResponsePermanentRedirect
|
||||
else:
|
||||
redirect_class = HttpResponseRedirect
|
||||
|
||||
# If it's a model, use get_absolute_url()
|
||||
if hasattr(to, 'get_absolute_url'):
|
||||
return redirect_class(to.get_absolute_url())
|
||||
|
||||
# Next try a reverse URL resolution.
|
||||
try:
|
||||
return redirect_class(urlresolvers.reverse(to, args=args, kwargs=kwargs))
|
||||
except urlresolvers.NoReverseMatch:
|
||||
# If this doesn't "feel" like a URL, re-raise.
|
||||
if '/' not in to and '.' not in to:
|
||||
raise
|
||||
|
||||
# Finally, fall back and assume it's a URL
|
||||
return redirect_class(to)
|
||||
|
||||
def _get_queryset(klass):
|
||||
"""
|
||||
Returns a QuerySet from a Model, Manager, or QuerySet. Created to make
|
||||
|
|
@ -59,4 +98,4 @@ def get_list_or_404(klass, *args, **kwargs):
|
|||
obj_list = list(queryset.filter(*args, **kwargs))
|
||||
if not obj_list:
|
||||
raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
|
||||
return obj_list
|
||||
return obj_list
|
||||
Loading…
Add table
Add a link
Reference in a new issue