Unique naming for file uploads

 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. slug filename by willhardy 3 years, 11 months ago
  2. Use the primary key in FileField and ImageField filenames by exogen 4 years, 8 months ago
  3. Unique FileFiled or FileFiled with custom validation and overwriting files on update by evilclay 2 years, 5 months ago
  4. Database file storage by powerfox 4 years, 4 months ago
  5. Easy file upload handler by mattdw 4 years, 9 months ago

Comments

(Forgotten your password?)