Login

Unique naming for file uploads

Author:
mindcruzer
Posted:
September 19, 2012
Language:
Python
Version:
1.4
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.