Django, how to see session data in the admin interface

Jon Cox picture Jon Cox · Feb 12, 2011 · Viewed 10.7k times · Source

I'm using Django sessions and I would like a way of seeing the session data in the admin interface. Is this possible?

I.e. for each session I want to see the data stored in the session database (which is essentially a dictionary as far as I can gather).

Currently I can just see a hash in the Session data field, such as:

gAJ9cQEoVQ5zb3J0aW5nX2Nob2ljZXECVQJQT3EDVQxnYW1lc19wbGF5ZWRxBH1xBVgLAAAAcG9z
dG1hbi1wYXRxBksDc1UKaXBfYWRkcmVzc3EHVQkxMjcuMC4wLjFxCFUKdGVzdGNvb2tpZXEJVQZ3
b3JrZWRxClUKZ2FtZV92b3Rlc3ELfXEMdS4wOGJlMDY3YWI0ZmU0ODBmOGZlOTczZTUwYmYwYjE5
OA==


I have put the following into admin.py to achieve this:

from django.contrib.sessions.models import Session
...
admin.site.register(Session)


In particular I was hoping to be able to see at least an IP address for each session. (Would be nice too if I could count how many sessions per IP address and order the IPs based on number of sessions in total for each.)

Thank you for your help :-)

Answer

Tomasz Zieliński picture Tomasz Zieliński · Feb 12, 2011

You can do something like this:

from django.contrib.sessions.models import Session
class SessionAdmin(ModelAdmin):
    def _session_data(self, obj):
        return obj.get_decoded()
    list_display = ['session_key', '_session_data', 'expire_date']
admin.site.register(Session, SessionAdmin)

It might be even that get_decoded can be used directly in list_display. And in case there's some catch that prevents this from working ok, you can decode the session data yourself, based on the linked Django source.