Django ImageField upload_to基于自定义函数的自定义路径

时间:2016-02-13 07:27:08

标签: python django upload models imagefield

我正在尝试使用与下面类似的upload_to属性在Django ImageField中设置上传路径。

模型

image = models.ImageField(upload_to=image_upload_location(image="logo"))

功能

def image_upload_location(filename, instance, *args, **kwargs):

  if image:
    defaultFolder = "images/default"
    logoFolder = "images/logo"
    generalFolder = "images/general"
    productsFolder = "images/products"
    if image == "logo":
      folder = logoFolder
    elif image == "general":
      folder = generalFolder
    elif image == "products":
      folder = "productsFolder"
    else:
      folder = defaultFolder

    return "%s/%s" % (folder, filename)

我收到以下错误:

TypeError: image_upload_location() missing 2 required positional arguments: 'filename' and 'instance'

我已尝试传递实例和文件名,但无法解决如何使其工作的问题。关于如何使这个工作的任何想法,以便我可以使用相同的功能ImageField,因为我试图通过创建一个函数来处理所有" set"位置。

我也不想要Django添加的日期字段。

[编辑] 我需要知道的主要内容是如何传递所需的变量" instance和filename"加上一个额外的变量" image"来自模型ImageField的功能。 : - )

1 个答案:

答案 0 :(得分:0)

你有两个文件名和实例作为你的函数的参数,你没有传递。如果不需要,我建议这样做。

def image_upload_location(*args, **kwargs):
    filename=kwargs.pop('filename', 'DEFAULT')
    instance=kwargs.pop('instance', 'DEFAULT')

或给他们默认

def image_upload_location(filename='DEFAULT', instance='DEFAULT', *args, **kwargs):

[编辑]

此外,您永远不会在您的函数中实例/抓取/设置“图像”。将其设置为参数,或从kwargs中弹出。

[编辑2016-01-15] - 这就是我想你想要的。

image = models.ImageField(upload_to=image_upload_location(image_type='logo', filename='filename.jpg'))

image = models.ImageField(upload_to=image_upload_location(filename='filename.jpg'))

image = models.ImageField(upload_to=image_upload_location('filename.jpg', 'logo'))

请参阅下面的所有不同组合示例

def image_upload_location(filename, image_type='', *args, **kwargs):
    if image_type=='logo':
        folder = 'images/logo'
    elif image_type=='general':
        folder = 'images/general'
    elif image_type=='products':
          folder = 'images/products'
    else:
          folder = 'images/default'

    return '%s/%s' % (folder, filename)

#All of the different ways to call it
print(image_upload_location('test.jpg')); #1 indexed argument, 1 default argument
print(image_upload_location('test2.jpg', 'logo')); #2 indexed arguments
print(image_upload_location('test3.jpg', image_type='logo')); #1 indexed argument, 1 named argument (indexed arguments can't come after named arguments)
print(image_upload_location(image_type='general', filename='test4.jpg')); #2 named arguments
print(image_upload_location(filename='test5.jpg', image_type='products')); #2 named arguments in a different order

此外,如果您不使用args和kwargs作为参数,则不需要包含它们。