[英]django file upload to dynamic path
I am trying to upload a file to django. 我正在尝试将文件上传到django。 So, I tried to use the code below to create a dynamic path for the file.
因此,我尝试使用下面的代码为文件创建动态路径。 But, it does not work.
但是,它不起作用。
I actually not sure how to use instance in model.py and how to pass path to def get_file_path. 我实际上不确定如何在model.py中使用实例以及如何将路径传递给def get_file_path。 Specifically, What I want is that pass the file path from the function in views.py.
具体来说,我想要的是从views.py中的函数传递文件路径。 For example, when I call something like docfile.save(filepath) , it will be saved in that filepath in django.
例如,当我调用docfile.save(filepath)之类的东西时,它将保存在django中的该文件路径中。 Can you help me for this?
你可以帮帮我吗?
An example: 一个例子:
docfile.save(path1)
it will be saved in /path1/file_name
Note: path1 could be anything and it is not related to any model field. 注意:path1可以是任何内容,它与任何模型字段无关。
You could for example have an extra field (eg path
) on the model that specifies the path which you could then access via instance.path
in get_file_path
. 例如,您可以在模型上有一个额外的字段(例如
path
),指定您可以通过get_file_path
instance.path
访问的路径。 You can't access arguments to save
in this function. 您无法访问要在此函数中
save
参数。
You can write a custom file field. 您可以编写自定义文件字段。
class MyFieldField(FileField):
def get_path(self, attname):
return 'path/to/%d' % self.id
def contribute_to_class(self, cls, name):
super(MyFileField, self).contribute_to_class(cls, name)
dispatcher.connect(self._post_init, signals.post_init, sender=cls)
def _post_init(self, instance=None):
if hasattr(instance, 'get_path'):
self.upload_to = instance.get_path(self.attname)
def db_type(self):
return 'varchar(100)'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.