Login

Custom Admin Redirects

Author:
leitjohn
Posted:
March 23, 2009
Language:
Python
Version:
1.0
Score:
1 (after 1 ratings)

This little bit of code will let you reference parts of the admin but lets you control where it returns to.

For instance, I have a list of objects in the admin and i want to have a delete link for each object. I don't want them to return to the changelist after a delete however, i want them to return to my list.

cheers

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
from django.http import HttpResponseRedirect


class AdminRedirectMiddleware:
	""" allows you to customize redirects with the GET line in the admin """

	def process_response(self, request, response):
		# save redirects if given
		if request.method == "GET" and request.GET.get("next", False):
			request.session["next"] = request.GET.get("next")

		# apply redirects
		if request.session.get("next", False) and \
		type(response) == HttpResponseRedirect and \
		request.path.startswith("/admin/"):
			path = request.session.get("next")
			del request.session["next"]
			return HttpResponseRedirect(path)
		return response

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 8 months ago

Comments

derek (on May 5, 2009):

Thanks, this has been really useful to me.

I did find one problem- URLs with no trailing slash fail with an AttributeError, cos request is a WSGIRequest and has no 'session' attr. This is nasty because it doesn't throw a 500 error.

I've wrapped it in a try block just now till I have time to look at what's going on.

#

bigfudge (on July 5, 2012):

@derek That's probably because django redirects to add the trailing slash, and the session is not available on the redirect. Catching AttributeError and returning the response is a reasonable workaround.

#

Please login first before commenting.