22

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?

user3025403
  • 1,070
  • 3
  • 21
  • 33

3 Answers3

35

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 %}
Ivan Semochkin
  • 8,649
  • 3
  • 43
  • 75
  • for use in development mode add this code in main urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) – nsola Jan 20 '21 at 09:11
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
  • 36,596
  • 57
  • 175
  • 260
1

You should use media path, instead static. See docs

Q-bart
  • 1,503
  • 4
  • 22
  • 41