Python Django app upload files

In this Python Django Tutorial, we will learn Python Django app upload files. And we’ll also see examples related to this. These are the following topics that we are going to discuss in this tutorial.

  • Python Django app upload files
  • Python Django model fields
  • Python Django File Upload
  • Python Django Image Upload
  • Python Django view uploaded files at front-end

Python Django app upload files

Uploading means sending a file from a local computer to a remote system, which stores a copy of the material being transferred. It is possible to upload images, videos, movies, music, sounds, freeware, shareware, and text files.

Python Django model fields

To upload files in Django, Django has different model fields. And, these fields are used to handle different files type.

There are two model fields in Django:

  • ImageField
  • FileField

Let’s discuss each field one by one to get an overview:

ImageField:

ImageField is a model field that exclusively accepts image formats for upload. And some command image file formats are as follow:

  • GIF (.gif)
  • PNG (.png)
  • TIFF (.tif, .tiff)
  • Bitmap (.bmp)
  • JPEG (.jpg, .jpeg)
  • EPS (.eps)
  • RAW Image Files (orf, .sr, .raw, .cr, .nef, and more)

The Pillow library is required by ImageField. To install the same run, follow these steps.

pip install Pillow

Syntax of ImageField:

field_name = models.ImageField(upload_to=None, height_field=None, width_field=None, max_length=100, **args)

FileField

FileField is a model field that is used to upload files. And, some of the common file formats are:

  • MP4
  • SVG
  • PDF
  • MP3
  • Docx

Syntax of FileField:

field_name = models.FileField(upload_to=None, max_length=254, **args)

Also, check: Login system in Python Django

Python Django File Upload

Create Project And App: Firstly, we have to create a project and app. So, to create it use the below define code.

# Project
django-admin startproject project_name

# App
python manage.py startapp app_name

Here, I create a project with the name PythonGuides and an app with the name home.

Install App: After, creating the project and app successfully. you have to install an App. For this, you have to add our app in the settings.py file.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'home',
]

To save uploaded files, modify settings: Now add the following lines to the end of the settings.py file.

import os
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
  • MEDIA URL: The URL endpoint is specified here. This is the URL where the user can upload their files from their browser.
  • MEDIA ROOT: This defines the root path where the file will be saved.
  • The second line directs Django to save all uploaded files in the BASE DIR, i.e., the project Directory, in a folder called ‘media’.
  • We must manually create the folder so that all uploaded files are saved in the media folder.

Media Folder: Create a new folder called ‘media’ in the project folder.

python django file upload
Python Django file upload

Project URLs: You have to add a link to your new app that is created. Add the below code snippets to the urls.py file of PythonGuides.

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

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

App URLs: You have to add the path of the function views. Add the below code snippets to the urls.py file of the home.

from django.urls import path,include
from . import views
urlpatterns = [
path('UploadFile', views.UploadFile, name='UploadFile'),
]

Create Model: In models.py, create a new Django Model “Blog” and then add the following code.

from django.db import models

class Blog(models.Model):
    author = models.CharField(max_length=100)
    title = models.CharField(max_length=200)
    file = models.FileField(upload_to='documents/')
  • We create the model CharField, which stores the name of the author who uploads a file.
  • Then, we create one more CharField, which stores the title of the file that the user uploads.
  • Then, we use the FileField used for files that the user will upload.
  • The upload_to option defines the location within the media where the file will be saved.

Create Form: We’ll now import the “Blog” Model into forms.py and create the “BlogForm” ModelForm.

from django import forms  
from .models import Blog

class BlogForm(forms.ModelForm):
    class Meta:
        model = Blog
        fields = ['author', 'title', 'file']

Create Views: Implement the form in the views.py file. Here, we need to upload the files. So, simply add the request.FILES along with the request.POST.

The syntax is as below:

form = BlogForm(request.POST,request.FILES)

Add, the following code snippets to the views.py file.

from django.shortcuts import render, HttpResponse
from .forms import BlogForm

def UploadFile(request):
    if request.method == 'POST':
        form = BlogForm(request.POST,request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponse('The file is saved')
    else:
        form = BlogForm()
        context = {
            'form':form,
        }
    return render(request, 'Upload.html', context)
  • Here, we create the UploadFile function.
  • Then, we check whether the request method is POST or not.
  • After this, we simply add a request.FILES along with the request.POST to the form method.
  • Here we use the is_valid() method in view functions as it returns values as True and False.
  • Then, we return to HttpResponse and also render to HTML template.

Create HTML Template: Now, create a Upload.html template that shows the form. Add the following code in the upload.html file.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload Files</title>
</head>

<body>
    <form method='post' enctype="multipart/form-data">
        {% csrf_token %}
        {{form.as_p}}
        <input type="submit" value="Submit">
    </form>
</body>

</html>
  • Now, create the <form> attribute in the template file.
  • Next, add the enctype =”multipart/form-data” otherwise, the form won’t work.
  • We also use the csrf_token tag is used in form to avoid malicious attacks.
  • Then, we use form.as_p tag to render Django forms as a paragraph.

Django Database Migrations: It is the process of transferring changes made to a model to the database schema.

Run the following commands in the terminal:

# Make Migartions

python manage.py makemigrations

# Migrate

python manage.py migrate
  • makemigrations: is used to make a migration file that includes code for a model’s tabular schema.
  • migrate: is used to builds tables in accordance with the migration file’s schema.

Run Server: Start the server and access the form by defining the URL as http://127.0.0.1:8000/UploadFile.

Command to run the server:

python manage.py runserver
python django app upload files
Django app upload files
upload files using python django app
Upload files using Python Django app

Here, Marry Smith upload the Introduction to Django file in Docx format.

file upload using python django
File upload using Python Django

When we click on Submit button, we move to HTTP Response that “The File is saved”.

View file in Media: You can see, the file is successfully stored in the Documents directory under the Media directory.

view file upload using python django
View file upload using Python Django

You can also upload pdf-based files. Let’s have a look at it.

app to upload files using python django
PDF File Upload App
django upload file app
Django upload file app
run file upload app
Run file upload app

Even you can upload files in mp4 format.

mp4 file upload app using django
MP4 file upload app using Django
djnago app upload mp4 files
Django app upload mp4 files

Read: Outputting Python to HTML Django

Python Django Image Upload

In this section, we’ll learn how to upload images in Django.

Create Project And App: First and foremost, we must develop a project and an app. So, to create it, use the defined code below.

# Project
django-admin startproject PythonGuides

# App
python manage.py startapp UploadApp

Here, I create a project with the name PythonGuides and an app with the name UploadApp.

Install App: After that, the project and app were successfully created. Now, you must install an application. You must include our app in the settings.py file to execute this.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'UploadApp',
]

To save uploaded files, modify settings: Now add the following lines to the end of the settings.py file.

import os
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
  • First, import os.
  • Then, to server the media files, we use MEDIA_URL.
  • After this, to specify the root path where the file will be saved, we use MEDIA_ROOT.

Media Folder: In the project folder, make a new folder called ‘media’.

python django image upload
Python Django image upload

Project URLs: You must include a link to your newly developed app. Add the following code snippets to PythonGuides’s urls.py file.

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

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

App URLs: The path to the function views must be included. Add the following code snippets to the UploadApp’s urls.py file.

from django.urls import path,include
from . import views
urlpatterns = [
path('UploadImage', views.UploadImage, name='UploadImage'),
]

Create Model: In models.py, create a new Django Model “Course” and then add the following code.

from django.db import models

class Course(models.Model):
    author = models.CharField(max_length=100)
    title = models.CharField(max_length=200)
    image = models.ImageField(upload_to='images/')
  • Here, we define the model CharField, which store the name of the author who upload a image and also the title of the image.
  • To upload the images, we use ImageField.
  • The upload_to option defines that image will saved under images directory within the media directory.

Create Form: We’ll now import the “Course” Model into forms.py and create the “CourseForm” ModelForm.

from django import forms  
from .models import Course

class CourseForm(forms.ModelForm):
    class Meta:
        model = Course
        fields = ['author', 'title', 'image']

Create Views: Implement the form in the views.py file. Here, we need to upload the image, so, simply add the request.FILES along with the request.POST.

from django.shortcuts import render, HttpResponse
from .forms import CourseForm

def UploadImage(request):
    if request.method == 'POST':
        form = CourseForm(request.POST,request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponse('The image saved successfully')
    else:
        form = CourseForm()
        context = {
            'form':form,
        }
    return render(request, 'upload.html', context)
  • Here, we create the UploadImage function which check whether the request method is POST or not.
  • After this, we simply add a request.FILES along with the request.POST to the form method.
  • Then, we use the is_valid() method in view functions as it returns values as True and False.
  • And in last, we return to HttpResponse and also render to HTML template.

Create HTML Template: Now, create a Upload.html template that shows the form. Add the following code in the upload.html file.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload Files</title>
</head>

<body>
    <form method='post' enctype="multipart/form-data">
        {% csrf_token %}
        {{form.as_p}}
        <input type="submit" value="Submit">
    </form>
</body>

</html>
  • Now, create the <form> attribute in the template file.
  • Next, add the enctype =”multipart/form-data” otherwise, the form won’t work.
  • We also use the csrf_token tag in form to avoid malicious attacks.
  • Then, we use form.as_p tag to render Django forms as a paragraph.

Django Database Migrations: Run the following commands in the terminal:

# Make Migartions

python manage.py makemigrations

# Migrate

python manage.py migrate
  • makemigrations: Makes migration file that have model’s schema.
  • migrate: Build tables according to migration file’s schema.

Run Server: Start the server and access the form by defining the URL as http://127.0.0.1:8000/UploadImage.

Command to run the server:

python manage.py runserver
python django app upload image
Preview Form in Browser

Example #1

In this example, we upload an image in png format.

app to upload image using python django
App to upload image using Python Django

When we click on Submit button HTTP Response displays.

django upload image app
Django upload image app

The uploaded file view in Images Directory within Media Directory.

django app upload png images
Django app upload png images

Example #2

In this example, we upload an image in jpeg format.

upload image using python django
Upload image using Python Django

The uploaded jpeg file view in Images Directory within Media Directory.

view image uploaded using python django
View image uploaded using Python Django

Example #3

In this example, we upload an image in gif format.

upload image using python django app
Upload image using Python Django app
django app upload gif
Django app upload gif

Read: Python Django vs ReactJS

Python Django view uploaded files at front-end

In this section, we’ll learn how to see uploaded images on the browser.

Create Project And App: Type the following command in the terminal.

# Project
django-admin startproject MyProject

# App
python manage.py startapp MyApp

Install App: Now, you must install an application. And add it in the settings.py file.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'MyApp,
]

To save uploaded files, modify settings: Now add the following lines to the end of the settings.py file.

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

Media Folder: In the project folder, make a new folder called ‘media’.

Python Django Image upload view on browser
Python Django Image upload view on browser

Project URLs: Add the following code in the MyProject’s urls.py file.

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('MyApp.urls'))
]

if settings.DEBUG:  
        urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
  • Here, we serve files uploaded by users from MEDIA_ROOT during development by adding static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT).
  • Here, MEDIA_URL is kept as ‘media’ and document_root is the location of the uploaded file inside media folder.
  • But, it only works when DEBUG is set to True and the URL specified in the settings is local.

App URLs: Add the following code in the MyApp’s urls.py file.

from django.urls import path
from . import views
urlpatterns = [
path('Upload', views.Upload, name='Upload'),
]

Create Model: Add the following code in the models.py file.

from django.db import models

class UploadImage(models.Model):
    title = models.CharField(max_length=200)
    image = models.ImageField(upload_to='images/')

Create Form: Add the following code in the forms.py file.

from django import forms  
from .models import UploadImage

class UploadImageForm(forms.ModelForm):
    class Meta:
        model = UploadImage
        fields = ['title', 'image']

Create View: Add the following code in the views.py file.

from django.shortcuts import render
from .forms import UploadImageForm

def Upload(request):
    if request.method == 'POST':
        form = UploadImageForm(request.POST,request.FILES)
        if form.is_valid():
            form.save()
            img_object = form.instance
            return render(request, 'ImageUpload.html', {'form': form, 'img_obj': img_object})
    else:
        form = UploadImageForm()
        context = {
            'form':form,
        }
    return render(request, 'ImageUpload.html', context)
  • We also create image objects and render them to HTML templates.

Create Template: Add the following code in the upload.html file.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload Files</title>
</head>

<body>
    <form method='post' enctype="multipart/form-data">
        {% csrf_token %}
        {{form.as_p}}
        <input type="submit" value="Submit">
    </form>
    {% if img_obj %}  
        <h3>Succesfully uploaded :</h3>  
        <img src="{{ img_obj.image.url}}" alt="connect" style="max-height:500px">  
    {% endif %}  
</body>

</html>
  • In HTML Template, we use the if tag which checks if an image object is there shows it on the browser.

Migrate Database: Run the following commands in the terminal.

# Make Migartions

python manage.py makemigrations

# Migrate

python manage.py migrate

Run Server: Run the following command in the terminal.

python manage.py runserver
python django view uploaded files at frontend
Form View
view uploaded files at frontend using python django
view uploaded files at frontend using Python Django

When we click on Submit Button. The output will be as below.

django view uploaded files at frontend example
Django view uploaded files at frontend example

From here, we conclude that we can view the uploaded files from the browser front-end.

Also, take a look at some more Python Django tutorials.

In this Python Django Tutorial, we discussed the Python Django App upload files. And also, discuss the following list of topics.

  • Python Django app upload files
  • Python Django model fields
  • Python Django File Upload
  • Python Django Image Upload
  • Python Django view uploaded files at front-end