This tag makes it easy to have a random rotation of images on a page. Don't forget to set your MEDIA_URL.
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
- Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
- Help text hyperlinks by sa2812 12 months ago
Comments
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.
#
Good point. I updated it to fix this, using
posixpath.join
(which works better for this example thanurlparse.urljoin
).#
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?
#
ext = os.path.splitext(filename)[1] + .lower()<br /> that could prevent missing from caps up exts.
#
Please login first before commenting.