2012-07-13 35 views
6

如何获取FileField的链接?我试过url领域,但它给人的文件路径:如何获取FileField中文件的链接?

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

回答

0

输出是根据你的设置文件,对服务的开发和/或生产staticfiles看看这里的理解:

Confusion in Django admin, static and media files

+0

哎呀,MEDIA_URL没有设置。 – jul 2012-07-13 16:20:14

+0

但我仍然得不到我想要的东西。比较我的编辑。 – jul 2012-07-13 17:23:35

0

我猜你定义为场:

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")