Code

Ticket #10194: redirect.diff

File redirect.diff, 1.8 KB (added by dcwatson, 5 years ago)

Shortcut and documentation

Line 
1Index: django/shortcuts/__init__.py
2===================================================================
3--- django/shortcuts/__init__.py        (revision 10020)
4+++ django/shortcuts/__init__.py        (working copy)
5@@ -5,7 +5,7 @@
6 """
7 
8 from django.template import loader
9-from django.http import HttpResponse, Http404
10+from django.http import HttpResponse, HttpResponseRedirect, Http404
11 from django.db.models.manager import Manager
12 from django.db.models.query import QuerySet
13 
14@@ -60,3 +60,11 @@
15     if not obj_list:
16         raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
17     return obj_list
18+
19+def redirect( obj ):
20+    """
21+    Returns a HttpResponseRedirect, calling get_absolute_url() on the passed
22+    argument if it exists.
23+    """
24+    redirect_to = hasattr(obj, 'get_absolute_url') and obj.get_absolute_url() or obj
25+    return HttpResponseRedirect( redirect_to )
26Index: docs/topics/http/shortcuts.txt
27===================================================================
28--- docs/topics/http/shortcuts.txt      (revision 10020)
29+++ docs/topics/http/shortcuts.txt      (working copy)
30@@ -151,3 +151,28 @@
31         my_objects = list(MyModel.objects.filter(published=True))
32         if not my_objects:
33             raise Http404
34+
35+``redirect``
36+============
37+
38+``django.shortcuts.redirect`` returns an ``HttpResponseRedirect`` object with
39+the given string or model instance.
40+
41+Required arguments
42+------------------
43+
44+``redirect_to``
45+    Either a string, or any object with a ``get_absolute_url()`` method defined
46+    for it.
47+
48+Example
49+-------
50+
51+The following example redirects to a newly-created model instance::
52+
53+    from django.shortcuts import redirect
54+
55+    def my_view(request):
56+        if request.method == 'POST':
57+            # Create a model instance here...
58+            return redirect(model_inst)