Random-image template tag

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import os
import random
import posixpath
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 posixpath.join(settings.MEDIA_URL, path, pick)
    

More like this

  1. Random code tag by aaloy 5 years, 10 months ago
  2. Frontend admin date picker widget by t_rybik 3 years, 1 month ago
  3. Login Required Middleware with Next Parameter by bernardoporto 6 months, 1 week ago
  4. Login Required Middleware by onecreativenerd 4 years, 6 months ago
  5. Handy tag for generating URLs to media files by Amr Mostafa 6 years, 1 month ago

Comments

jnievas (on May 1, 2007):

The latest os.path.join will make this version not compatible for running over Windows, since URLs always have forward slashes. Should be changed to use always a forward slash.

#

pbx (on May 16, 2007):

Good point. I updated it to fix this, using posixpath.join (which works better for this example than urlparse.urljoin).

#

alimony (on March 24, 2010):

If the specified folder were not found it throws a 500 error, but I'd rather have it fail silently. This is also the approach recommended by Django:

"render() should never raise TemplateSyntaxError or any other exception. It should fail silently, just as template filters should." http://docs.djangoproject.com/en/dev/howto/custom-template-tags

I made this change by replacing line 24 with:

try:
    filenames = [f for f in os.listdir(fullpath) if is_image_file(f)]
except OSError:
    return ""

#

losttrekker (on June 11, 2010):

I'm sure its possible, but I'm failing to grasp it right now. How can I get this snippet to grab only images of a specific size?

#

(Forgotten your password?)