Image upload with preview in Django

In this tutorial, we will work on Django framework and will learn how to upload the image to Django and preview it. Django is a Python web framework that helps us in developing web applications quickly and effectively.

Image Upload functionality

In models.py

Models.py is used for creating the database in Django. We have to store images and thus required an Imagefield.

from django.db import models

class UploadedImage(models.Model):
    image = models.ImageField(upload_to='media/')

In forms.py

To handle Image upload functionality.

from django import forms
from .models import UploadedImage

class ImageUploadForm(forms.ModelForm):
    class Meta:
        model = UploadedImage
        fields = ['image']

In views.py

This file has the code to handle the POST and GET request from the html.

from django.shortcuts import render, redirect
from .forms import ImageUploadForm
from .models import UploadedImage

def upload_image(request):
    if request.method == 'POST':
        form = ImageUploadForm(request.POST, request.FILES)
        if form.is_valid():
            uploaded_image = form.save()
            image_url = uploaded_image.image.url
            return redirect('upload_success', image_url=image_url)
    else:
        form = ImageUploadForm()
    return render(request, 'upload_image.html', {'form': form})

def upload_success(request, image_url):
    latest_uploaded_image = UploadedImage.objects.last()
    # Check if an image was uploaded
    if latest_uploaded_image:
        # Get the URL of the uploaded image
        image_url = latest_uploaded_image.image.url
    else:
        # If no image was uploaded, set image_url to None
        image_url = None
        
    return render(request, 'upload_success.html', {'image_url': image_url})

In app/urls.py

Create a python file named urls.py in your app directory. This file contains path of url page combined with the functions of views.py

from django.urls import path
from . import views

urlpatterns = [
    path('upload/', views.upload_image, name='upload_image'),
    path('upload/success/<path:image_url>/', views.upload_success, name='upload_success'),  # Add a path parameter for image_url
]

In project/urls.py

In this file, we will simply import the urls of app. In this way, our works get simpler and error free. To account the image urls, we have to use MEDIA_URLand MEDIA_ROOT

from django.contrib import admin
from django.urls import path, include  

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('app.urls')),  
]

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

In settings.py

Ensure that you have included the app name in the INSTALLED_APPS list. Also, define the MEDIA_URL and MEDIA_ROOT here.

# Media files (uploaded by users)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Include this code at the bottom of settings.py file.

Templates

Now, our backend work is over and have to develop webpage for it. Create the templates directory in your app directory. In this directory, html files will be there. We need two web pages, first allowing the user to upload the image, and second showing that the upload is successful and the image preview.

upload_image.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload Image</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        function previewImage(input) {
            var imagePreview = $('#imagePreview');
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    imagePreview.attr('src', e.target.result).show();
                }
                reader.readAsDataURL(input.files[0]);
            } else {
                imagePreview.hide();
            }
        }
    </script>
</head>
<body>
    <h2>Upload Image</h2>
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <input type="file" name="image" onchange="previewImage(this);">
        <br>
        <img id="imagePreview" src="#" alt="Image Preview" style="max-width: 300px; max-height: 300px; display: none;">
        <br>
        <input type="submit" value="Upload">
    </form>
</body>
</html>

upload_success.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload Success</title>
</head>
<body>
    <h2>Upload Successful!</h2>
    <img src="{{ image_url }}" alt="Uploaded Image" style="max-width: 300px; max-height: 300px;">
    <br>
    <a href="{% url 'upload_image' %}">Upload another image</a>
</body>
</html>

 

Leave a Reply

Your email address will not be published. Required fields are marked *