Django1.9 Loads the image method uploaded via ImageField

  • 2020-09-28 08:59:00
  • OfStack

It is assumed that you are uploading images via ImageField of models and expect them to appear on the foreground img tag. The key to accessing an image is whether it can be accessed through the right path.

In models.py there is image as follows


image = models.ImageField(upload_to='images/%Y/%m', verbose_name=' File thumbnail ')

Use the img tag to display on display pages such as show.html


<img class="center-block thumbnail" src="{{result.object.image.url }}" alt="" />

But here {{result. object. image. url}} just read out the above model upload_to the path below, didn't really show up. To display in the template, you also need to configure in urls.py and settings.py

The next step in your ES30en.ES31en configuration is as follows:


from django.conf.urls import include, url
from django.conf import settings
from django.conf.urls.static import static

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

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

In setttings.py, MEDIA_URL and MEDIA_ROOT are configured, where the media configuration is defined, that is, the directory where the ImageField parameter upload_to in the model is defined


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

At this point, we are able to correctly access the images uploaded via ImageFields. Below is the description above the official document

Specific related documents

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

In your settings file, you must define MEDIA_ROOT as the path for Django to store the uploaded files (for performance reasons, these files cannot be stored in the database). Define 1 MEDIA_URL as the base URL or directory. Make sure this directory can be written to the account used by web server.

Add the FileField or ImageField fields to the model to define the upload_to parameter, which is a subdirectory of MEDIA_ROOT to hold the uploaded files.

The database holds only the path to this file (relative to MEDIA_ROOT). You will probably want to use the convenient url attribute provided by Django. For example, if your ImageField is named mug_shot, you can use {{object.mug_shot. url}} on template to get the absolute path to your photos.

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


Related articles: