要使用Django FileField还是FilePathField? [英] To use Django FileField or FilePathField?

查看:93
本文介绍了要使用Django FileField还是FilePathField?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于要使用哪个字段,我有些困惑.我需要的只是一个将保存文件(音频和/或图像的另一个文件)的字段

I'm a bit confused about which field to use. What I need is just a Field that will hold a file (audio and/or another one for an image)

FileField似乎是专门用于上传的,我认为这对于我需要的内容来说有点过头了,我也不喜欢它每次都会自动上传并将文件重命名为唯一文件名(file_FHjgh758.txt)的方式.上载了一些内容.

The FileField seems to be specifically for uploading and I think it is a bit of overkill for what I need, I also don't like how it will automatically upload and rename the files to a unique filename (file_FHjgh758.txt) everytime something is uploaded.

我在FilePathField中遇到的问题是,它似乎需要绝对路径,这显然对开发人员和生产人员而言是不同的,我通过将其添加到模型中来解决了这个问题……

The problem I have with the FilePathField is that it seems to require an absolute path, which would obviously be different from dev to production, I got around this by adding this to the model...

import os

class Foo(models.Model):

    path = os.path.dirname(os.path.dirname(__file__))
    path = os.join(path, 'media')
    audio = models.FilePathField(path=path)

我不知道这是否安全或适当,并且在线或文档中没有很多可供借鉴的示例.

I have no idea if this is safe or proper, and there aren't many examples online or in the docs to draw from.

为清楚起见,我只想拥有一个字段,我可以将其指向系统中某处的文件(音频或图像).这样做的最佳方法是什么?

To be clear, I just want to have a field which I can point to a file (audio or image) somewhere in my system. What would be the best way to go about doing this?

推荐答案

如果要引用文件系统上已经存在的文件,而不是用户上载的文件,则 FilePathField 是您要使用的文件想要.

If you want to refer to files that are already on your filesystem rather than user uploaded files, then FilePathField is the one that you want.

在这方面,一些评论:

  • 请勿指向应用程序源代码树内的路径.那不安全.

  • Don't point to a path that is inside your app's source tree. That is not safe.

您可以使用设置或环境变量来处理开发路径与生产路径,例如,将 FILE_PATH_FIELD_DIRECTORY 设置放入开发/生产设置文件中,然后从您的应用中引用此设置:

You can use settings or environment variables to handle development vs. production paths, e.g., put a FILE_PATH_FIELD_DIRECTORY setting in your development/production settings files and refer to this setting from your app:

from django.conf import settings

class Foo(models.Model):
    audio = models.FilePathField(path=settings.FILE_PATH_FIELD_DIRECTORY)

这篇关于要使用Django FileField还是FilePathField?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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