Skip to content

Instantly share code, notes, and snippets.

@night-crawler
Created August 9, 2013 13:50
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save night-crawler/6193730 to your computer and use it in GitHub Desktop.
Save night-crawler/6193730 to your computer and use it in GitHub Desktop.
Save last visited pages with title and last access time in Django templates. Gist provides two methods: "save_visited" and "load_visited"
# -*- coding: utf-8 -*-
from django import template
from django.utils.encoding import force_unicode
from django.utils import timezone
from django.core.cache import cache
# import datetime
# from django.conf import settings
# from django.utils.formats import sanitize_separators
# from django.utils.html import conditional_escape as esc
register = template.Library()
def ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[-1].strip()
else:
ip = request.META.get('REMOTE_ADDR')
return ip
def get_user_identification(request):
"""
get the identification for user
if user is an anon, use session if we can, otherwise use pair of ip and user agent
if user is authenticated, make the visited pages global for any session
"""
if request.user.is_authenticated():
identify_by = request.user.id
else:
if hasattr(request, 'session') and request.session.session_key:
identify_by = request.session.session_key
else:
user_agent = unicode(request.META.get('HTTP_USER_AGENT', '')[:255], errors='ignore')
identify_by = '%s:%s' % (ip(request), user_agent)
return identify_by
@register.simple_tag(takes_context=True, name='save_visited')
def save_visited(context, title, **kwargs):
request = context['request']
# store last five pages
identify_by = get_user_identification(request)
visited_pages = cache.get('visited_pages_%s' % identify_by, [])[:4]
# context.use_tz - why None if set True in settings?
# may be we should save datetime.now() and convert it in getter?
now = timezone.now()
bundle = force_unicode(title), request.get_full_path()[:255], now
visited_pages.insert(0, bundle)
cache.set('visited_pages_%s' % identify_by, visited_pages, 60*60*24)
return title
@register.simple_tag(takes_context=True, name='load_visited')
def load_visited(context, variable, **kwargs):
identify_by = get_user_identification(context['request'])
context[variable] = cache.get('visited_pages_%s' % identify_by, [])
return u''
@night-crawler
Copy link
Author

Usage in a template:

{% block title %}{% save_visited _("Profile setup") %}{% endblock %}
...
{% load_visited 'visited' %}
{% for title, uri, dt in visited %}
    <a href="{{ uri }}">{{ title }} {% trans "at" %} {{ dt }}</a><br/>
{% endfor %}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment