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'))
...
Comments