简体   繁体   中英

Dynamic File Path in Django and South

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

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

I think you can get away here with Unipath .

Unipath usage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM