Django中的动态文件路径 [英] Dynamic File Path in Django
问题描述
- user_12
--- photo_1
- - photo_2
--- user_ 13
---- photo_1
我发现了一个相关的问题: Django自定义图像上传字段与动态路径
在这里,他们说我们可以更改upload_to路径,并导致 https://docs.djangoproject.com/en/stable/topics/files/ doc。在文档中,有一个例子:
from django.db import models
from django.core.files。存储导入FileSystemStorage
fs = FileSystemStorage(location ='/ media / photos')
class Car(models.Model):
...
photo = models.ImageField(storage = fs)
但是,这还不是动态的,我想给汽车ID到图像名称,我不能分配在汽车定义完成之前的id。那么我如何创建一个车ID?
您可以在 upload_to
参数中使用可调用,而不是使用自定义存储。请参阅文档,以及请注意,当调用函数时,主键可能尚未设置(因为上传可能在对象保存到数据库之前被处理),所以使用 ID
可能不可能。你可能会考虑在模型上使用另一个字段,如slug。例如:
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)
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
I found a related question : Django Custom image upload field with dynamic path
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)
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 ??
You can use a callable in the upload_to
argument rather than using custom storage. See docs, and note the warning there that the primary key may not yet be set when the function is called (because the upload may be handled before the object is saved to the database), so using ID
might not be possible. You might wan 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)
then:
photo = models.ImageField(upload_to=get_upload_path)
这篇关于Django中的动态文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!