Upon saving me model \'Products\' I would like the uploaded image to be named the same as the pk for example 22.png or 34.gif I don\'t want to change the format of the image jus
Django 1.7 and newer won't make migration with function like this. Based on answer by @miki725 and this ticket, you need to make your function like this:
import os
from uuid import uuid4
from django.utils.deconstruct import deconstructible
@deconstructible
class UploadToPathAndRename(object):
def __init__(self, path):
self.sub_path = path
def __call__(self, instance, filename):
ext = filename.split('.')[-1]
# get filename
if instance.pk:
filename = '{}.{}'.format(instance.pk, ext)
else:
# set filename as random string
filename = '{}.{}'.format(uuid4().hex, ext)
# return the whole path to the file
return os.path.join(self.sub_path, filename)
FileField(upload_to=UploadToPathAndRename(os.path.join(MEDIA_ROOT, 'upload', 'here'), ...)