简体   繁体   English

如何在Django的ImageField的路径中设置变量?

[英]How can I set variable in the path of ImageField of Django?

This is my models.py : 这是我的models.py

class Group_Photo(models.Model):

    group_id = models.ForeignKey(Group)
    photo = models.ImageField(upload_to="static/image/group/" + group_id + "/")

I'd like to upload images to a directory which is for a group. 我想将图像上传到一个群组的目录中。 For example, if the group_id = 3 , 例如,如果group_id = 3

upload_to="static/image/group/3/"

How should I do? 我应该怎么做?

Sorry, this is the error. 抱歉,这是错误。

File "/models.py", line 161, in Group_Photo photo = models.ImageField(upload_to="static/image/group/" + group_id + "/") TypeError: Can't convert 'ForeignKey' object to str implicitly Group_Photo照片= models.ImageField(upload_to =“ static / image / group /” + group_id +“ /”)中的文件“ /models.py”,第161行TypeError:无法将“ ForeignKey”对象隐式转换为str

The upload_to argument can be a function, as described in the documentation : 文档中所述, upload_to参数可以是一个函数:

def group_based_upload_to(instance, filename):
    return "image/group/{}/{}".format(instance.group.id, filename)

class Group_Photo(models.Model):
    group = models.ForeignKey(Group)
    photo = models.ImageField(upload_to=group_based_upload_to)

The function takes two arguments - instance of the model to which the file is being attached and the original name of the file. 该函数带有两个参数-文件附加到的模型的实例和文件的原始名称。 It has to return a relative path under witch the file will be saved. 它必须在巫婆下返回一个相对路径,文件将被保存。 It will be appended to the path defined in the MEDIA_ROOT setting. 它将被附加到MEDIA_ROOT设置中定义的路径。

The example above uses directories based on group's numeric id. 上面的示例使用基于组的数字ID的目录。 You can obviously use other fields, for example to use the slug (if it has one) just replace instance.group.id with instance.group.slug . 您显然可以使用其他字段,例如使用slug(如果有),只需将instance.group.id替换为instance.group.slug

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

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