Django How To Upload Images using Pillow Python Imaging Library
In this article, we will learn how to upload images in a Django application using Pillow Python Imaging Library. https://pypi.org/project/Pillow/
models.py
#models.py from django.db import models class Image(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to='images') def __str__(self): return self.title class Meta: db_table = "myapp_image"The upload_to parameters specify the location where images will be stored which for this model is MEDIA_ROOT/images/
Install Pillow by running the following command in your shell.
pip install Pillow
settings.py
# Base url to serve media files
MEDIA_URL = '/media/'
# Path where media is stored
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
urls.py file
#urls.py from django.contrib import admin from django.urls import path from myapp import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',views.index), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)forms.py
#forms.py from django import forms from myapp.models import Image class ImageForm(forms.ModelForm): """Form for the image model""" class Meta: model = Image fields = ('title', 'image')
#views.py from django.shortcuts import render, redirect from myapp.forms import ImageForm def index(request): """Process images uploaded by users""" if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): form.save() # Get the current instance object to display in the template img_obj = form.instance return render(request, 'index.html', {'form': form, 'img_obj': img_obj}) else: form = ImageForm() return render(request, 'index.html', {'form': form})
//templates/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>upload imagae</title> </head> <body> <p><h1>Django How To Upload Images using Pillow Python Imaging Library</h1></p> <p><h4>pip install Pillow</h4></p> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> {% if img_obj %} <h3>Succesfully uploaded : {{img_obj.title}}</h3> <img src="{{ img_obj.image.url}}" alt="connect" style="max-height:300px"> {% endif %} </body> </html>