Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django image field default static file

Tags:

django

I was wondering if there is a way to use an static image file as a default for an ImageField?

I'm asking this because if you write something like this because first, I'm not able to upload media folder to my github repository because I store in there the user uploads, and the default file always be the same, so I want to serve the default from static but the user uploads from media directory.

If you use this:

image = models.ImageField(upload_to=/upload/folder/, default=/img/default.jpg, blank=True, null=True)

It will try to load the default image from the media directory.

like image 526
Kevin Ramirez Zavalza Avatar asked Dec 08 '17 23:12

Kevin Ramirez Zavalza


1 Answers

UPDATE: This answer no longer works. Since version 1.9, Django removes the leading / from the file path to convert it to a relative path and then appends /media/ to the path.

This change was made due to this ticket: https://code.djangoproject.com/ticket/25905

Alternative: I like this answer as an alternative.


Original answer:

First, look at the these two paths:

/img/default.jpg    -   Absolute Path (starts with slash)
img/default.jpg     -   Relative Path (doesn't start with slash)

Now, if your default path is absolute, then Django will not convert the url to /media/.../. Django only converts the relative paths.

So, if you want to serve the default file from static folder, you can just set an absolute path to your file like - /static/img/default.jpg.


Extra:

You can even verify this. Django uses urllib.parse.urljoin to create the url. Try this:

>>> media_url = '/media/'
>>> abs_url   = '/img/default.jpg' # absolute url
>>> rel_url   = 'img/default.jpg'  # relative url

>>> from urllib.parse import urljoin # in Python 2: from urlparse import urljoin

>>> urljoin(media_url, abs_url) # test with absolute url
'/img/default.jpg'
>>> urljoin(media_url, rel_url) # test with relative url
'/media/img/default.jpg'
like image 153
xyres Avatar answered Oct 21 '22 08:10

xyres