[英]Django models.FileField - store only the file name not any paths or folder references
I'm using Django's Admin site to manage some data - but not building a webapp. 我正在使用Django的管理站点来管理一些数据-但未构建Webapp。 I need the file upload field to store only the file name in the database. 我需要文件上传字段以仅将文件名存储在数据库中。
Right now I can get absolute paths like: /Users/me/uploads/file.png 现在,我可以获得绝对路径,例如:/Users/me/uploads/file.png
Or using the upload_to parameter get something like this in the database: uploads/file.png 或使用upload_to参数在数据库中获得以下内容:uploads / file.png
How can I get it to be this: file.png 我怎么能这样:file.png
EDIT: 编辑:
I'm taking the sqlite database and using in another client - so having any paths in the db entry doesn't make sense in my case. 我正在使用sqlite数据库并在另一个客户端中使用-因此在我的情况下,在db条目中包含任何路径都没有意义。
Thanks! 谢谢!
I would keep the FileField and use python os.path.basename to extract the filename. 我会保留FileField并使用python os.path.basename提取文件名。
This can be encapsulated with a property 可以用属性封装
class MyModel(models.Model):
file = models.FileField(...)
@property
def filename(self):
return os.path.basename(self.file.name)
The upload_to
arg of the FileField
can be a callable. 该upload_to
的的ARG FileField
可以是可调用的。 see the docs 看文档
If you really need to only store the file name, I think you can do something like this. 如果您真的只需要存储文件名,我想您可以做这样的事情。 I did'nt try myself but I think it works. 我没有尝试过自己,但我认为它可行。
def only_filename(instance, filename):
return filename
class MyModel(models.Model):
file = models.FileField(upload_to=only_filename)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.