Ticket #10194: redirect.diff

File redirect.diff, 1.8 KB (added by Dan Watson, 15 years ago)

Shortcut and documentation

  • django/shortcuts/__init__.py

     
    55"""
    66
    77from django.template import loader
    8 from django.http import HttpResponse, Http404
     8from django.http import HttpResponse, HttpResponseRedirect, Http404
    99from django.db.models.manager import Manager
    1010from django.db.models.query import QuerySet
    1111
     
    6060    if not obj_list:
    6161        raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
    6262    return obj_list
     63
     64def redirect( obj ):
     65    """
     66    Returns a HttpResponseRedirect, calling get_absolute_url() on the passed
     67    argument if it exists.
     68    """
     69    redirect_to = hasattr(obj, 'get_absolute_url') and obj.get_absolute_url() or obj
     70    return HttpResponseRedirect( redirect_to )
  • docs/topics/http/shortcuts.txt

     
    151151        my_objects = list(MyModel.objects.filter(published=True))
    152152        if not my_objects:
    153153            raise Http404
     154
     155``redirect``
     156============
     157
     158``django.shortcuts.redirect`` returns an ``HttpResponseRedirect`` object with
     159the given string or model instance.
     160
     161Required arguments
     162------------------
     163
     164``redirect_to``
     165    Either a string, or any object with a ``get_absolute_url()`` method defined
     166    for it.
     167
     168Example
     169-------
     170
     171The following example redirects to a newly-created model instance::
     172
     173    from django.shortcuts import redirect
     174
     175    def my_view(request):
     176        if request.method == 'POST':
     177            # Create a model instance here...
     178            return redirect(model_inst)
Back to Top