How to get a link to a file in FileField?

How can I get a FileField link? 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 expected to get http://<mydomain>/media/files/reference/1342188147.zip

How can i get this? Do I need to build a string manually?

EDIT

My MEDIA_URL has not been set, but I still cannot 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 the 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 programmatically, a.file = "/some/path/to/file.txt" , the file does not load into MEDIA_ROOT . How to upload a file to the directory specified by upload_to , i.e. in my case /home/xxx/media/file.txt ?

+6
source share
2 answers

The output is based on your settings file; look here to understand how to serve static files during development and / or production:

Confusion in Django admins, static and media files

0
source

I assume that you have a field defined as:

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

In other words, is it possible that 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") 
0
source

Source: https://habr.com/ru/post/920431/


All Articles