How to get the link of the file in a FileField?
Asked Answered
R

2

7

how can I get the link of a FileField? I tried the url field, but it gives the file path:

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'

I was expecting to get http://<mydomain>/media/files/reference/1342188147.zip

How can I get that? Do I have to build the string manually?

EDIT

My MEDIA_URL was not set, but I still can't get it to work:

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

in shell

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

Then I get for a.path:

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

and for a.url:

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

When done programmatically, a.file = "/some/path/to/file.txt", the file is not uploaded to MEDIA_ROOT. How can I upload a file in the directory defined by upload_to, i.e. in my case /home/xxx/media/file.txt?

Retina answered 13/7, 2012 at 15:40 Comment(0)
G
-1

The output is based on your settings file, have a look here for an understanding on serving staticfiles in development and/or production:

Confusion in Django admin, static and media files

Graphy answered 13/7, 2012 at 16:0 Comment(0)
S
-2

I'm guessing you have the field defined as:

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

in other words is it possible you have defined an absolute path for the upload_path property of the field ?

Try something like

from django.conf import settings
picture = models.ImageField(upload_to=settings.MEDIA_ROOT + "files/reference")
Stoa answered 13/7, 2012 at 16:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.