timestamp media

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import os
from django.conf import settings

@register.simple_tag
def tsmedia(media):
    """
    timestamps media to avoid caching of changed file
    simple usage: {% tsmedia "css/style.css" %}
    output: {{ MEDIA_URL }}css/styler.css?<< seconds since the epoch >>
    """
    path = os.path.join(settings.MEDIA_ROOT, *media.split("/"))
    if os.path.exists(path):
        t = int(os.path.getmtime(path))
        return "%s%s?%s" % (settings.MEDIA_URL, media, t)
    return ""

Comments

theperitus (on September 26, 2008):

Have a look at http://github.com/peritus/django_hashedmedia/

That's the far superior solution.

#

dnordberg (on September 26, 2008):

Also this is a dup of http://www.djangosnippets.org/snippets/946/, which includes additional information on usage and possible issues

#

mikko (on September 26, 2008):

i knew it had to be a dupe, i just couldn't find it for some odd reason... why is the django_hashedmedia superior?

#

dnordberg (on September 27, 2008):

django_hashedmedia is good if you are distributing your media off more than one host (because then modification times may differ), otherwise, i think it's a bit much for a something that can be solved using a simple templatetag, also you have to call the management command each time you make changes.

#

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.