【Django】How to upload image

In today’s article, I will try to create a web app that uploads and displays images in Django.

It is an application to select and upload photos. The name of the photo, the photo, and the date and time of posting are displayed.

Library installation

You need a library called pillow to handle images. Please install it with the following command.

Add directory for media

Add or modify settings.py as follows.

ai_webapp/settings.py

Create a folder named “media” under the project folder.

URL setting

Add the following settings to urls.py of the project.

ai_webapp/urls.py

Please note that without these two lines, the image will not be displayed.

model

It is a model for handling images.

By setting upload_to to ‘documents’, images will be saved in “/media/documents”.

Form

View

template

migration

Management tool

It is a method to delete the unnecessary image from the management screen.

Enter an appropriate username, email address and password.

admin.py

You can access the management page with the following command.

Reference

https://matthiasomisore.com/web-programming/display-image-in-a-django-template-using-imagefield/