A note on HttpResponseRedirect with pagination in Django

When redirect a user after she submits data in the Django view by returning a HttpResponseRedirect object, I always use request.path as the destination.

return HttpResponseRedirect(request.path)

The problem is request.path returns the full path to the requested page, but not including the parameters (and the domain), so it will be annoying if I employ a pagination mechanism for the view. For example, if the user is on page 2 and submit data:

http://mydomain.com/myview/?page=2

print request.path

/myview/

So the user will be always redirected back to the first page. In this case, if I want to redirect the user to the page before she submits data, I need to use this as the destination instead:

request.get_full_path()

request.get_full_path() will return the full path (exclude the domain) along with the parameters (page=):

print request.get_full_path()

/myview/?page=2


Another note is that you must call get_full_path with a parentheses:
...
return HttpResponseRedirect(request.get_full_path())
...


For more information, please read the Django documentations: https://docs.djangoproject.com/en/dev/ref/request-response/

Comments