How to get the link of the file in a FileField?

jul picture jul · Jul 13, 2012 · Viewed 11k times · Source

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?

Answer

Hedde van der Heide picture Hedde van der Heide · Jul 13, 2012

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