rename uploaded image based on the field that its uploaded from

You could create 2 separate functions, either explicit or implicit with lambda:


# target determines 'head' vs 'body'
def wrapper(instance, filename, target): ...

# in your model:
    ...
    head_image = models.ImageField(upload_to=lambda inst, fn: wrapper(inst, fn, 'head'))
    body_image = models.ImageField(upload_to=lambda inst, fn: wrapper(inst, fn, 'body'))

or use a decorated function closure (prolly easier to read):

def wrapper(target):
    def inner(instance, filename):
        ...
    return inner

# in your model:
    ...
    head_image = models.ImageField(upload_to=wrapper('head'))
    body_image = models.ImageField(upload_to=wrapper('body'))
1 Like