How to File Upload in Django?

Published On: 03/09/2022 | Category: Django


Hi Dev,

I will explain step by step tutorial django file upload example. I’m going to show you about how to upload a file in django. you will learn python django file upload example. if you have question about django files upload example tutorial then I will give simple example with solution. Follow bellow tutorial step of how to upload csv file upload in django.

Here, we will install django and create a simple form with a file input field that you can use to select multiple files. after submitting the form we will store those files in a folder and database.

Django framework the file data is store into request.FILES. you need a FileField form that a view will handle this form and this form will receive file data in request.FILES which is a dictionary containing a key for each FileField. So let’s say if your form has an input field with name file and form has an attribute enctype="multipart/form-data", then file data can be accessible as request.FILES['file']. If your form does not have attribute enctype="multipart/form-data" then request.FILES['file'] will be empty.

Here i explained simply step by step example of django multiple file upload example in database.

Step 1: Create a Project

In 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 example
Step 2: Create a App

Now we'll create a single app called core to store a list of files name. We're keeping things intentionally basic. Stop the local server with Control+c and use the startapp command to create this new app.

python3 manage.py startapp core
Step 3: Update setting.py

In this step we require to do two things in our settings.py file.one is register our new app in INSTALLED_APPS within our settings.py second is to configure our media folder. Add the below lines to your settings.py file:

Next, you need to add it in the settings.py file as follows:

import os

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

....
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = "/media/"
Step 4: Database Setup

Next step, we will modify the settings.py file and update the database settings to configure the mydb database:

settings.py
DATABASES = {  
    'default': {  
        'ENGINE': 'django.db.backends.mysql',  
        'NAME': 'example',  
        'USER':'root',  
        'PASSWORD':'root',  
        'HOST':'localhost',  
        'PORT':'3306'  
    }  
}  
Step 5: Create a validators.py

In this step we will create a custom validators.py in our core app this file will be check file will be must be given list of extension array then if not file extension is not given list of extension array it will be raise error:

core/validators.py
import os
from django.core.exceptions import ValidationError

def validate_file_extension(value):
    ext = os.path.splitext(value.name)[1]  # [0] returns path+filename
    valid_extensions = ['.pdf', '.csv', '.doc', '.docx', '.xlsx', '.xlx']
    if not ext.lower() in valid_extensions:
        raise ValidationError('Unsupported file extension!')
Step 6: Create a Model

In this step we will require the database model for storing contacts.Open the core/models.py file and add the following code:

core/models.py
from django.db import models
from .validators import validate_file_extension

class Document(models.Model):
    file = models.FileField(upload_to="documents/%Y/%m/%d",
                                validators=[validate_file_extension]
                            )

Next, you need to migrate your database using the following command:

python manage.py makemigrations
python manage.py migrate
Step 7: Create a Form

In this step We need to create a form that will be used .like add a bootstrap class and validation etc.. plus we need to add custom styling.

core/forms.py
from django import forms
from .models import *
from django.utils.translation import gettext as _

class DocumentForm(forms.ModelForm):

    file = forms.FileField(label=_('Choose File'),
                            required=True, 
                            error_messages = {'required':'The file field is required.','invalid':_("Files only")}, 
                            widget=forms.FileInput(attrs={'class': 'form-control custom-file-input','id' : 'customFile'})
                        )

    class Meta:
        model = Document
        fields = ['file',]
Step 8: Creating the Views

In this step, we need to configure our views. The file_upload page will just be a template and store to multiple image database and our media folder.So, open the core/views.py file and add:

core/views.py
from django.shortcuts import render
from .forms import *
from .models import *
from django.contrib import messages
import os

# Create your views here.

def file_upload(request):

    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)

        if form.is_valid():
            form.save()
            messages.success(request, 'File Upload Successfully')
    else:
        form = DocumentForm()

    return render(request, 'index.html', {'form' : form})
Step 9: Creating the Template

Next, open the core/templates/index.html file and the add:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tuts-Station.com</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/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <style type="text/css">
        body{
            background-color: #f7fcff;
        }
    </style>
</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">
                        <h4>How to File Upload in Django? - <span class="text-primary">Tuts-Station.com</span></h4>
                    </div>
                    <div class="card-body">
                        <form method = "post" enctype="multipart/form-data" novalidate>
                            {% csrf_token %}
                            <label>File:</label>
                            <div class="custom-file">
                                {% for field in form %}
                                    <label class="custom-file-label" for="customFile">{{ field.label }}</label>
                                    {{ field }}
                                    <small class="text-danger mt-2">{{ field.errors|striptags }}</small>
                                {% endfor %}
                            </div>
                            <small class="mt-2">(File extension must be pdf, csv, doc, docx, xlsx, xlx format.)</small>
                            <div class="row mt-4">
                                <div class="col-lg-12 text-center">
                                    <button class="btn btn-success">Submit</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
<script type="text/javascript">

    /*------------------------------------------
    --------------------------------------------
    Custom File Input 
    --------------------------------------------
    --------------------------------------------*/
    $(".custom-file-input").on("change", function() {
        var fileName = $(this).val().split("\\").pop();
        $(this).siblings(".custom-file-label").addClass("selected").html(fileName);
    });
   </script>
</html>
Step 10: Creating Urls

In this section, we need a urls.py file within the core app however Django doesn't create one for us with the startapp command. Create core/urls.py with your text editor and paste below code:

core/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('file/', views.file_upload, name="file_upload"),
]

Next, we require to add a URL path for our example project which can be done by importing include and setting a path for it.

example/urls.py
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('core.urls')),
]

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

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/file address with a web browser.

I Hope It will help you....

django file upload example, how to upload a file in django, python django file upload example, django files upload example tutorial,how to upload csv file upload in django, django file upload with preview, how to upload pdf in django, upload files in django