[Django]-Django ImageField upload_to path

36πŸ‘

βœ…

Your image would be uploaded to the media folder, so it’s better to change the path in the model like images/, and they will be uploaded 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 these images, 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 %}

17πŸ‘

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')
πŸ‘€doniyor

1πŸ‘

You should use media path, instead static. See docs

πŸ‘€Q-bart

Leave a comment