【问题标题】:How to get the link of the file in a FileField?如何在 FileField 中获取文件的链接?
【发布时间】:2012-07-13 15:40:27
【问题描述】:

如何获得FileField 的链接?我尝试了url 字段,但它给出了文件路径:

In [7]: myobject.myfilefield.path
Out[7]: u'/home/xxxx/media/files/reference/1342188147.zip'

In [8]: myobject.myfilefield.url
Out[8]: u'/home/xxxx/media/files/reference/1342188147.zip'

我期待收到http://<mydomain>/media/files/reference/1342188147.zip

我怎样才能得到它?我必须手动构建字符串吗?

编辑

我的 MEDIA_URL 没有设置,但我仍然无法使用它:

settings.py

MEDIA_ROOT = '/home/xxx/media/'
MEDIA_URL = 'http://xxx.com/media/'

models.py

class Archive(models.Model):

    #...
    file = models.FileField(upload_to="files")

在外壳中

a = Archive()
a.file = "/some/path/to/file.txt"
a.save()

然后我得到a.path

"/some/path/to/file.txt"

对于a.url

"http://xxx.com/media/some/path/to/file.txt"

以编程方式完成时,a.file = "/some/path/to/file.txt",文件不会上传到MEDIA_ROOT。如何在upload_to定义的目录中上传文件,即在我的情况下/home/xxx/media/file.txt

【问题讨论】:

    标签: django filefield


    【解决方案1】:

    输出基于您的设置文件,请查看此处以了解在开发和/或生产中提供静态文件:

    Confusion in Django admin, static and media files

    【讨论】:

      【解决方案2】:

      我猜你的字段定义为:

      picture = models.ImageField(upload_to="/home/xxx/media/files/reference")
      

      换句话说,您是否可以为字段的 upload_path 属性定义绝对路径?

      试试类似的东西

      from django.conf import settings
      picture = models.ImageField(upload_to=settings.MEDIA_ROOT + "files/reference")
      

      【讨论】:

        猜你喜欢
        • 2012-11-04
        • 1970-01-01
        • 2019-01-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多