summaryrefslogtreecommitdiffstats
path: root/agenda/templatetags/random_image.py
diff options
context:
space:
mode:
Diffstat (limited to 'agenda/templatetags/random_image.py')
-rwxr-xr-xagenda/templatetags/random_image.py27
1 files changed, 27 insertions, 0 deletions
diff --git a/agenda/templatetags/random_image.py b/agenda/templatetags/random_image.py
new file mode 100755
index 0000000..cdb3d15
--- /dev/null
+++ b/agenda/templatetags/random_image.py
@@ -0,0 +1,27 @@
+import os
+import random
+import posixpath
+import path
+from django import template
+from django.conf import settings
+
+register = template.Library()
+
+def is_image_file(filename):
+ """Does `filename` appear to be an image file?"""
+ img_types = [".jpg", ".jpeg", ".png", ".gif"]
+ ext = os.path.splitext(filename)[1]
+ return ext in img_types
+
+@register.simple_tag
+def random_image(path):
+ """
+ Select a random image file from the provided directory
+ and return its href. `path` should be relative to MEDIA_ROOT.
+
+ Usage: <img src='{% random_image "images/whatever/" %}'>
+ """
+ fullpath = os.path.join(settings.MEDIA_ROOT, path)
+ filenames = [f for f in os.listdir(fullpath) if is_image_file(f)]
+ pick = random.choice(filenames)
+ return path.join(settings.MEDIA_URL, path, pick)