Skip to content

Instantly share code, notes, and snippets.

@RaD
Created August 6, 2012 21:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RaD/3278531 to your computer and use it in GitHub Desktop.
Save RaD/3278531 to your computer and use it in GitHub Desktop.
Keep user sorting and filtering settings of models with Django's admin site
# -*- coding: utf-8 -*-
import re
from django.shortcuts import redirect
PREF_VAR = 'ADMIN_PER_USER_PREF'
ORDER_VAR = 'o'
FILTER_TAIL = '__exact'
PATH = '/admin/storage/'
EXCLUDE_RE = re.compile(r'(\d+|add)\/$')
class ChangelistPreferencesMiddleware(object):
u"""
Allow users to keep their sorting and filtering preferences
for selected (see PATH variable) models in admin site of Django.
"""
def process_request(self, request):
if request.method == 'GET' \
and request.path.startswith(PATH) \
and not EXCLUDE_RE.search(request.path):
prefs = request.session.get(PREF_VAR, dict())
opts = prefs.get(request.path, dict())
if 0 < len(request.GET):
# sorting
if ORDER_VAR in request.GET:
opts[ORDER_VAR] = request.GET[ORDER_VAR]
# filtering
for key in filter(lambda x: x.endswith(FILTER_TAIL), request.GET):
opts[key] = request.GET[key]
# save the state
prefs[request.path] = opts
request.session[PREF_VAR] = prefs
else:
if 0 < len(opts):
# apply the state
return redirect(u'%s?%s' % (
request.path,
'&'.join(map(lambda x: '%s=%s' % x, opts.items())))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment