Gonzalo Dambra
Gonzalo Dambra

Reputation: 980

Django: Dynamic storage folder for models.ImageField

I have an ImageField in my model which I want to store the image url dynamically depending on a user session var. Imaginary like this:

logo = models.ImageField(null=True, upload_to = 'empresas/'+codEmp+'/logo/')

And the var codEmp is a session variable: request.session['codEmp']

Therefore if the codEmp of a user is for example 'McDonalds' it should save the following path: 'empresas/McDonalds/logo/imaginary_picture.jpg'.

I tried by init but I can't finish it and I'm not sure if it'll work.

class Empresa(models.Model):
    def __init__(self, filter_on, *args, **kwargs):
        super(Empresa, self).__init__(*args, **kwargs)
        codEmp = filter_on
        logo = models.ImageField(null=True, upload_to = 'empresas/'+codEmp+'/logo/')

I tried to do this in the ModelForm but it seems that forms.ImageField doesn't have an upload_to attribute.

Upvotes: 0

Views: 216

Answers (1)

albar
albar

Reputation: 3100

The upload_to parameter may be a callable expected to accept 2 parameters: instance and filename. See here.

Upvotes: 2

Related Questions