简体   繁体   English

Django和South的动态文件路径

[英]Dynamic File Path in Django and South

I'm having a problem setting a dynamic path to my imageField. 我在设置imageField的动态路径时遇到问题。

This is my models.py 这是我的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. 这实际上在更新对象时工作正常,但是当我尝试插入新元素时,插入失败,因为在那一刻self不存在。

I've tried another solution here whose proposal is overriding the ImageField method to customize upload_to. 我在这里尝试了另一个解决方案其建议是重写ImageField方法来自定义upload_to。

The problem is that I use South and it's quite difficult to manage custom fields 问题是我使用South, 管理自定义字段非常困难

I use Django 1.5. 我使用Django 1.5。 I would like to know if exists any easy way to manage dynamic file path in django 我想知道是否存在任何简单的方法来管理django中的动态文件路径

Thanks 谢谢

Alternatively you can override the save method to move the file to the correct path. 或者,您可以覆盖save方法以将文件移动到正确的路径。

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一起离开这里。

Unipath usage Unipath用法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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