Django template tag

import os
import random
import posixpath
from django import template
from django.conf import settings

register = template.Library()

def files(path, types=[“.jpg”, “.jpeg”, “.png”, “.gif”]):
fullpath = os.path.join(settings.MEDIA_ROOT, path)
return [f for f in os.listdir(fullpath) if os.path.splitext(f)[1] in types]

@register.simple_tag
def random_image(path):
pick = random.choice(files(path))
return posixpath.join(settings.MEDIA_URL, path, pick)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s