How to upload images in Django

Steps to upload images in Django

The following steps outline a simple image file upload in Django.

These steps assume you clearly understand the basic structure of a Django project.

Step 1

Add the following code to the end of your settings.py file.

MEDIA_URL = '/media/'

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

MEDIA_ROOT indicates the root folder the server uses for media storage.
MEDIA_URL is the reference URL the browser uses to access the file over HTTP.

Step 2

Create a urls.py file in your app folder and not the project folder if you don’t already have one. Then add the following code to it.

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)

In this urls.py file, there is a check for the DEBUG mode.This can be found in settings.py file.

With settings.py DEBUG status set as true, the if statement is executed serving the files with django.contrib.staticfiles.views.serve() in development server. It makes serving these files in the local server easier.

Step 3

Create your model class in the models.py file. It may be as simple as the example below or significantly more complex.

models.py

from django.db import models

class Student(models.Model):
    name = models.CharField(max_length=50)
    avatar = models.ImageField(upload_to='uploads/')

def __str__(self):
     return self.title

In the code above, the models.ImageField indicates the folder that holds the image and creates a row on the database table that contains the URL that points to the image.

Step 4

Using Django’s model form, create a form class for handling our example student form and link it with the model in the form.py file.

form.py

from django import forms
from .models import *
  
class StudentForm(forms.ModelForm):
  
    class Meta:
        model = Student
        fields = ['name', 'avatar']

With the help of this form, Django will present two fields to the user through the HTML form: one for name input, which will be text type, and one for image upload input.

Step 5

Next, create the HTML form that displays the input fields as indicated in the forms.py file.

studentform.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Students</title>
</head>
<body>
    <form method = "post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Upload</button>
    </form>
</body>
</html>

The form input displays as a paragraph because of the form.as_p python command.

Step 6

Next, create your view function in view.py to handle the upload of the form and its data.

views.py

from django.http import HttpResponse
from django.shortcuts import render, redirect
from .forms import *
  
/*#Create your views here.*/
def avatarView(request):
  
    if request.method == 'POST':
        form = StudentForm(request.POST, request.FILES)
  
        if form.is_valid():
            form.save()
            return redirect('success')
    else:
        form = StudentForm()
    return render(request, 'studentform.html', {'form' : form})
  
  
def uploadok(request):
    return HttpResponse(' upload successful')

When a form is submitted, the avatarView function checks if there is a POST request. If there is, the StudentForm class in form.py is called to handle the form, while image data goes into the request.FILES list object.
The validity of the form is also checked. If valid, the form and its input is saved and the user is redirected to a submit successful page. If it is not valid, the form is displayed again.

The success view function will display a submit successful message.

Step 7

Lastly, update the urls.py file we created earlier in our app folder as follows.

urls.py

from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from .views import *
  
urlpatterns = [
    path('image_upload/', avatarView, name = 'image_upload'),
    path('success/', uploadok, name = 'success'),
]
  
if settings.DEBUG:
        urlpatterns += static(settings.MEDIA_URL,
                              document_root=settings.MEDIA_ROOT)