Pergunta

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?

Foi útil?

Solução

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

Outras dicas

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")
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top