Django ImageField upload_to path

Question:

I’m having trouble understanding and using Django’s ImageField.

I have a model:

class BlogContent(models.Model):
    title = models.CharField(max_length=300)
    image = models.ImageField(upload_to='static/static_dirs/images/')
    description = models.TextField()

My file system is currently:

src
 |---main_project
 |---app_that_contains_blog_content_model
 |---static
       |---static_dirs
                |---images

When I run the server and go to the Admin page, I can add BlogContent objects. After choosing an image for the image field, the image has a temporary name. However, after I save this object I can’t find the image in the folder specified by the upload_to path.

What is the correct way to do this?

Asked By: user3025403

||

Answers:

You should use media path, instead static. See docs

Answered By: Q-bart

Your image would be uploaded to the media folder, so it’s better to change path in the model like images/, and they will be upload to media/images

In settings.py add this

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

In url.py

from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [....
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

And then, if you want to display all this image, use something like this
in view.py
BlogContent.objects.all()

And render it like this:

{% for img in your_object %}
    <img src="{{ img.image.url }}" >
{% endfor %}
Answered By: Ivan Semochkin

static in upload_to doesnot make sense, since user-uploaded images go into media/ folder.. you need these:

image = models.ImageField(upload_to='blog/%Y/%m/%d')

and all images land in:

media/blog/2016/01/02/img_name.jpg

you access it in template like this:

<img src="{{ blog.image.url }}">

in settings:

import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Answered By: doniyor
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.