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