Will & Skill Developers

Will & Skill Developers


Thoughts, snippets and ideas from the team at Will & Skill AB, Stockholm.

Webdeveloper @ Will & Skill

Share


Unique and slugify Django filename

Mohammed HammoudMohammed Hammoud

utils.py

from django.utils.text import slugify
import time
import os

class UniqueFilenameUtil:
    def __init__(self, directory):
        self.directory = directory

    def unique_filename(self, instance, filename):
        epoch_time = int(time.time())
        slugify_filename = slugify(filename)
        new_filename = u'{}-{}'.format(epoch_time, slugify_filename)
        return os.path.join(self.directory, new_filename)

Example of usage

from utils import UniqueFilenameUtil

superhero_name_util = UniqueFilenameUtil(directory='superheroes/images/')
car_name_util = UniqueFilenameUtil(directory='cars/images/')

class Superhero(models.Model):
    image = ImageField(upload_to=superhero_name_util.unique_filename)

class Car(models.Model):
    image = ImageField(upload_to=car_name_util.unique_filename)

Webdeveloper @ Will & Skill

Comments