How to Image Upload in Python Django ?

Hi Dev,
I am going to explain you example of how to image upload in python django. This tutorial will give you simple example of how to upload image in python django. this example will help you how to upload image in django form. you can understand a concept of django image upload example. you will do the following things for how to image upload in python django blog.
Here i will give you we will help you to give example of how to upload image in django. So let's see the bellow example:
Step 1 : Create a ProjectIn this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:
django-admin startproject exampleStep 2 : Create a App
python3 manage.py startapp image
Next, you need to add it in the settings.py file as follows:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'image', ]Step 3 : Database Setup
Next step, we will modify the settings.py file and update the database settings to configure the mydb database:
settings.pyDATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'example', 'USER':'root', 'PASSWORD':'root', 'HOST':'localhost', 'PORT':'3306' } }Step 4 : Update Setting.py File
Next step, we will modify the settings.py file and add the below code:
- MEDIA_ROOT: is for server path to store files in the computer.
- MEDIA_URL:is the reference URL for browser to access the files over Http.
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/'And in the urls.py we should edit the configuration like this example/urls.py
from django.conf import settings from django.conf.urls.static import static if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)Step 5 : Create a Model
In this step we will require the database model for storing contacts.Open the image/models.py file and add the following code:
image/models.pyfrom django.db import models # Create your models here. class UserImage(models.Model): name = models.CharField(max_length=50) image = models.ImageField(upload_to='images/')
After creating these model, you need to create migrations using the following command:
Step 5 : Create a Migrationspython manage.py makemigrations
After successfully run the above command go to the image/migrations/0001_initial.py
image/migrations/0001_initial.py# Generated by Django 4.0.5 on 2022-06-27 09:36 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='UserImage', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('image', models.ImageField(upload_to='images/')), ], ), ]
Next, you need to migrate your database using the following command:
python manage.py migrateStep 5 : Create a Form
In this step we will require here we are dealing with model form to make content easier to understand. and add the following code:
image/forms.pyfrom django import forms from .models import * class UserForm(forms.ModelForm): class Meta: model = UserImage fields = ['name', 'image']Step 6 : Creating the Views
In this step, we need to create the views for performing fetch record to the database.Open the image/views.py file and add:
image/views.pyfrom django.http import HttpResponse from django.shortcuts import render, redirect from .forms import * from django.contrib import messages # Create your views here. def userProfile(request): if request.method == 'POST': form = UserForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.success(request, 'Image Upload Successfully') else: form = UserForm() return render(request, 'profileImg.html', {'form' : form})Step 7 : Creating Django Templates
In this step i will use bootstrap 4 crispy forms if you don't know about that so i will already post article first you can read this Bootstrap 4 Crispy Forms
Next, open the image/templates/profileImg.html file and the add:
/image/templates/profileImg.html{% load crispy_forms_tags %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Profile Image</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script> </head> <body> <div class="container mt-5 pt-5"> <div class="row d-flex justify-content-center"> <div class="col-md-8"> {% if messages %} <div class="alert alert-success alert-dismissible"> <button type="button" class="close" data-dismiss="alert">×</button> {% for message in messages %} {{ message }} {% endfor %} </div> {% endif %} <div class="card"> <div class="card-header bg-secondary text-white"> <h3>How to image Upload in Python Django ? - Tuts-Station.com</h3> </div> <div class="card-body"> <form method = "post" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <hr> <div class="row"> <div class="col-md-12 text-center"> <button type="submit" class="btn btn-success">Upload</button> </div> </div> </form> </div> </div> </div> </div> </div> </body> </html>Step 8 : Creating Urls
In this section, we’ll create the urls to access our views.Go to the urls.py example/urls.py file and update it as follows:
example/urls.pyfrom django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from image.views import * urlpatterns = [ path('admin/', admin.site.urls), path('image-upload', userProfile, name = 'image_upload'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)Step 9 : Run the Server
In this step, we’ll run the local development server for playing with our app without deploying it to the web.
python manage.py runserver
Next, go to the http://localhost:8000/ address with a web browser.
I Hope It will help you....