3

I'm having a problem setting a dynamic path to my imageField.

This is my models.py

class Imagen(models.Model):

def get_upload_path(self, filename):
  return os.path.join(
  "img/experiencias/experiencia_%d" % self.id_experiencia.id, 'ficha' + '_' + filename)

nombre = models.CharField(max_length=50)
id_experiencia = models.ForeignKey(TipoExperiencia)
imagen = models.ImageField(upload_to= get_upload_path)
caption = models.CharField(max_length=150,blank=True)
alt = models.CharField(max_length=100)

This is a solution that I've found here

This actually works fine when updating objects, but when I try to insert new elements, the inserts fail because in that moment self does not exists.

I've tried another solution here whose proposal is overriding the ImageField method to customize upload_to.

The problem is that I use South and it's quite difficult to manage custom fields

I use Django 1.5. I would like to know if exists any easy way to manage dynamic file path in django

Thanks

Community
  • 1
  • 1
Lucas
  • 597
  • 3
  • 15

2 Answers2

1

Alternatively you can override the save method to move the file to the correct path.

class Model(models.Model):
  def save(self, *args, **kwargs):
    instance = super(Model, self).save(*args, **kwargs)
    # your logic here to change the file location
    return instance
James Lin
  • 25,028
  • 36
  • 133
  • 233
0

I think you can get away here with Unipath.

Unipath usage

Viren Rajput
  • 5,426
  • 5
  • 30
  • 41