Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
django

How to upload images in Django

NDUKWE CHIDERA K.

Overview

Django is a web framework powered by python and is widely known as the web framework for perfectionists. It enables you to get your web applications up and running with minimal codes.

It is structured in the MVTModel View Template framework pattern and handles some operations, like uploading files and images, in unique ways.

What to know before uploading your image

  • request.FILES holds data about files submitted to the server.

  • The form used to submit the file must have the enctype="multipart/form-data" attribute included.

  • The form should have a method value of POST and should have the {% csrf_token %} included as well. The input for the image submission must have the input type attribute value of the file.

  • The Django model ImageField creates a column that holds a string value. This string is the URL to the image location on the file system.

  • Images uploaded are not saved to the database. Instead, they’re saved to the folder you indicate when creating your image model. Save this folder in the media_url location you indicate in the settings.py file.

That is the basics of image/file upload in Django. Let’s now see the steps to upload an image.

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)

You’re done setting up, now run migration to create your model and run your server. With the server up and running, go to your browser and run your application. You should see something that looks like so:

RELATED TAGS

python
django
RELATED COURSES

View all Courses

Keep Exploring