如何根据Django中的字段名更改ImageField的upload_to参数?

时间:2015-05-20 12:23:04

标签: django models filefield imagefield

我想根据Django管理员用户提供的字段值将图像上传到媒体根目录。这是我编写的代码,我知道upload_to参数导致了问题。但我不知道如何让它发挥作用。

models.py

class Info(models.Model):
    file_no = models.CharField(max_length=100)
    date = models.DateField()
    area = models.IntegerField(default=0.00)
    mouja = models.CharField(max_length=100)
    doc_type_choices = (
            ('deed', 'Deed'),
            ('khotian', 'Khotian'),
        )
    doc_type = models.CharField(max_length=50,
                                choices=doc_type_choices,
                                default='deed')
    doc_no = models.CharField(max_length=50)

    def __unicode__(self):
        return self.file_no

class Image(models.Model):
    info = models.ForeignKey('Info')
    content = models.ImageField(upload_to=self.info.mouja/self.info.doc_type)

    def __unicode__(self):
        return self.info.file_no

每当我运行 python manage.py makemigrations 时,它会显示 NameError:name' self'未定义 在此先感谢您的帮助!

2 个答案:

答案 0 :(得分:6)

upload_to关键字中,您需要提供一个您将定义的函数,例如:

def path_file_name(instance, filename):
    return '/'.join(filter(None, (instance.info.mouja, instance.info.doc_type, filename)))

class Image(models.Model):
    content = models.ImageField(upload_to=path_file_name)

来自Django documentation: Model field reference

  

这也可以是一个可调用的函数,例如一个函数,它将被调用以获取上传路径,包括文件名。这个callable必须能够接受两个参数,并返回一个Unix风格的路径(带有正斜杠)以传递给存储系统。

在此callable中,在特定情况下为path_file_name函数,我们从instance字段构建路径,该字段是Image模型的特定记录。

filter函数会删除列表中的所有None项,而join函数会通过将所有列表项与/结合来构建路径。

答案 1 :(得分:1)

这是有效的原始代码。以防任何人需要它。

def path_file_name(instance, filename):
    return '/'.join(filter(None, (instance.info.mouja, instance.info.doc_type, filename)))