Login

Unique naming for file uploads

Author:
mindcruzer
Posted:
September 19, 2012
Language:
Python
Version:
1.4
Tags:
files path naming uploads
Score:
0 (after 0 ratings)

This snippit can be used to generate unique file names for uploads. upload_to allows a callable, but only provides two arguments: instance and filename. In order to prevent dumping all of the files for a model into one directory, this utilizes the partial decorator from functools, which essentially allows adding an extra argument to the function. The returned path will be of the form: [model name]/[field_name]/[random hash].[filename extension]

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from django.contrib.auth.models import User

def make_filepath(field_name, instance, filename):
    '''
        Produces a unique file path for the upload_to of a FileField.

        The produced path is of the form:
        "[model name]/[field name]/[random name].[filename extension]".
    '''
    new_filename = "%s.%s" % (User.objects.make_random_password(10),
                             filename.split('.')[-1])
    return '/'.join([instance.__class__.__name__.lower(),
                     field_name, new_filename])

...

from django.db import models
from functools import partial

# Example use on a model
class SomeModel(models.Model):
    ...
    image = models.ImageField(upload_to=partial(make_filepath, 'image'))
    ...

More like this

  1. Unique FileFiled or FileFiled with custom validation and overwriting files on update by evilclay 4 years, 3 months ago
  2. Human readable file names decorator by maxk 4 years ago
  3. Prefetch id for Postgresql backend by bretth 3 years ago
  4. Convert LaTeX templates to various output formats by blizz 8 years, 1 month ago
  5. Database file storage by powerfox 6 years, 2 months ago

Comments

Please login first before commenting.