SoFunction
Updated on 2024-11-15

Django1.9 method of loading images uploaded via ImageField

Let's assume here that you are uploading an image through the ImageField of the models and expect it to be displayed in the frontend img tag. The key to being able to access the image is to be able to access it via the correct path.

There are images in it as follows

image = (upload_to='images/%Y/%m', verbose_name='Document thumbnails')

Use the img tag in the display page to display the

<img class="center-block thumbnail" src="{{ }}" alt="" />

However, {{}} just reads out the path under the model upload_to above, and doesn't really show it. To display it in the template, you need to add the following lines to the and configure the

Next, configure the following in your:

from  import include, url
from  import settings
from  import static

urlpatterns = [
  '''Your other url configurations'''
]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

The MEDIA_URL and MEDIA_ROOT are configured in the MEDIA_URL and MEDIA_ROOT section, which defines the media-related configurations, i.e., the directory where the upload_to parameter is located in the ImageField of the model.

MEDIA_URL = '/media/'
MEDIA_ROOT = (BASE_DIR, 'media')

At this point, we are able to correctly access images uploaded through ImageFields, here are some instructions from the official documentation above

Specific related documents

Calling a FileField or ImageField in a model (see below) requires the following steps:

In your settings file, you have to define MEDIA_ROOT as the path where Django will store the uploaded files (for performance reasons, these files can't be stored in the database). Define a MEDIA_URL as the base URL or directory. Make sure that this directory is writable by the account used by the web server.

Add a FileField or ImageField field to the model, defining the upload_to parameter as a subdirectory of MEDIA_ROOT where the uploaded files will be stored.

All that is stored in the database is the path to this file (as opposed to MEDIA_ROOT). You'll probably want to use the handy url attribute provided by Django. For example, if your ImageField is named mug_shot, you can use {{ object.mug_shot.url }} in the template to get the absolute path to your photo.

For example, if your MEDIA_ROOT is set to '/home/media' and upload_to is set to photos/%Y/%m/%d. The '%Y/%m/%d' of upload_to is formatted by strftime(); '%Y' will be formatted as a four-digit year, '%m' as a two-digit month and '%d' as a two-digit day. is formatted as a four-digit year, '%m' is formatted as a two-digit month and '%d' is a two-digit day. If you uploaded a file on Jan.15.2007, it will be saved in the /home/media/photos/2007/01/15 directory.

Above this Django1.9 load through the ImageField uploaded image method is all I share with you, I hope to give you a reference, and I hope you support me more.