django - 在视图中设置upload_to [英] django - set the upload_to in the view
问题描述
我有一个用于存储文件的模型:
I have a model for storing files:
class AFile(models.Model):
path = models.CharField(max_length=256)
name = models.CharField(max_length=256)
file = models.FileField(upload_to=get_path)
有许多保存文件的视图。我想为每个路径分开一条路径。所以我把路径放在模型中,并在get path函数中使用。像这样:
there are many views that save files. I want a seperate path for each. so I put path in the model and use that in the get path function. like so:
afile = AFile(path='blah/foo/', name='filex.jpg')
afile.save()
所以文件在正确的位置。但是我真的不想在我的数据库中存储路径和名称字段,它只在那里生成一个路径。任何方式实现同样的事情没有额外的模型字段?
so the file is in the right spot. But I don't really want to store the path and name field in my database, its only there to generate a path. any way to achieve this same thing without extra model fields?
推荐答案
这里的问题是 upload_to
仅在模型上定义 FileField
或 ImageField
时可用。对该字段的任何后续访问都会返回一个 FieldFile
实例,该实例无法访问定义的 upload_to
。长和短,没有办法在初始定义之后更改该方法。
The problem here is that upload_to
is only available when defining the FileField
or ImageField
on the model. Any subsequent access to the field returns a FieldFile
instance, which doesn't have access to the defined upload_to
. Long and short, there's no way to alter the method after it's initially defined.
但是,您可能可以在其周围执行一种最终的运行。请注意,我没有实际尝试过这个,但是它应该工作:
However, you might be able to do a sort of end-run around it. Note that I haven't actually tried this, but it should work:
首先在你的模型上定义一个将有简单任务的方法在模型上设置一个实例变量:
First define a method on your model that will have the simple task of setting an instance variable on the model:
def set_upload_to_info(self, path, name):
self.upload_to_info = (path, name)
然后,在你的 upload_to
方法,您可以测试这些属性的存在并使用它们:
Then, inside your upload_to
method, you can test for the presence of these attributes and use them if they are:
def my_upload_to(instance, filename):
if hasattr(instance, 'upload_to_info'):
path, name = instance.upload_to_info
# do something and return file path
else:
# standard upload_to bit here
然后在您的看法中,您只需要调用您创建的方法之前保存模型:
Then in your view, you just need to call the method you create before you save the model:
afile.set_upload_to_info(path, name)
afile.save()
这篇关于django - 在视图中设置upload_to的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!