Django 中的动态文件路径 [英] Dynamic File Path in Django

查看:19
本文介绍了Django 中的动态文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 django 中生成动态文件路径.我想制作一个这样的文件系统:

I'm trying to generate dynamic file paths in django. I want to make a file system like this:

 -- user_12
     --- photo_1
     --- photo_2
 --- user_ 13
     ---- photo_1

我发现了一个相关的问题:Django 自定义图片上传字段与动态路径

I found a related question : Django Custom image upload field with dynamic path

在这里,他们说我们可以更改upload_to 路径并导致https://docs.djangoproject.com/en/stable/topics/files/ 文档.在文档中,有一个例子:

Here, they say we can change the upload_to path and leads to https://docs.djangoproject.com/en/stable/topics/files/ doc. In the documentation, there is an example :

from django.db import models
from django.core.files.storage import FileSystemStorage

fs = FileSystemStorage(location='/media/photos')

class Car(models.Model):
    ...
    photo = models.ImageField(storage=fs)

但是,这仍然不是动态的,我想将 Car id 赋予图像名称,并且在 Car 定义完成之前我无法分配 id.那么如何创建带有汽车 ID 的路径?

But, still this is not dynamic, I want to give Car id to the image name, and I cant assign the id before Car definition completed. So how can I create a path with car ID ??

推荐答案

您可以在 upload_to 参数中使用可调用对象,而不是使用自定义存储.请参阅文档,并注意那里的警告,即调用该函数时可能尚未设置主键.之所以会发生这种情况,是因为可能会在对象保存到数据库之前处理上传,因此可能无法使用 ID.您可能需要考虑在模型上使用其他字段,例如 slug.例如:

You can use a callable in the upload_to argument rather than using custom storage. See the docs, and note the warning there that the primary key may not yet be set when the function is called. This can happen because the upload may be handled before the object is saved to the database, so using ID might not be possible. You might want to consider using another field on the model such as slug. E.g:

import os
def get_upload_path(instance, filename):
    return os.path.join(
      "user_%d" % instance.owner.id, "car_%s" % instance.slug, filename)

然后:

photo = models.ImageField(upload_to=get_upload_path)

这篇关于Django 中的动态文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆