How to File Upload Using Ajax in Django?

Hi Dev,
In this example, you will learn how to file upload using ajax in django. Here you will learn django ajax file upload example. let’s discuss about django jquery ajax file upload example tutorial. this example will help you how to upload files using django jquery and ajax.
Here, in this example, we will create "Document" table with a file column. Then we will create a form with file input, when you submit it will send the image via jquery ajax request and store the image into the folder and database.
You can use these examples with django3 (django 3) version.
Here i explained simply step by step example of how to file upload using ajax in django.
Step 1: Create a ProjectIn 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 exampleStep 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 coreStep 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:
settings.pyimport 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: 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.pyimport 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 5: 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.pyfrom 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 migrateStep 6: 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.pyfrom 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 7: 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.pyfrom django.shortcuts import render from .forms import * from .models import * from django.contrib import messages from django.http import JsonResponse # Create your views here. def file_upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return JsonResponse({'success': True, 'message': 'File Uploaded Successfully!'}) else: return JsonResponse({'error': True, 'errors': form.errors}) else: form = DocumentForm() return render(request, 'index.html', {'form': form})Step 8: Creating the Template
Next, open the core/templates/index.html file and the add:
core/templates/index.html<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <title>Tuts-Station.com</title> <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-lg-8"> <div class="card"> <div class="card-header"> <h4>How to File Upload using Ajax in Django? - <span class="text-primary">Tuts-Station.com</span></h4> </div> <div class="card-body"> <div class="row success-msg-main" style="display: none;"> <div class="col-lg-12"> <div class="alert alert-success success-msg"></div> </div> </div> <form enctype="multipart/form-data" method="post" id="id_ajax_upload_form" novalidate> {% csrf_token %} <div class="custom-file"> {% for field in form %} <label class="custom-file-label" for="customFile">{{ field.label }}</label> {{ field }} {% 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-primary">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); }); /*------------------------------------------ -------------------------------------------- Ajax File Upload -------------------------------------------- --------------------------------------------*/ $('#id_ajax_upload_form').submit(function(e){ e.preventDefault(); $form = $(this) var formData = new FormData(this); $.ajax({ url: '{% url "file_upload" %}', type: 'POST', data: formData, success: function (response) { $('.error').remove(); if (response.success) { $('.success-msg-main').css('display', 'block'); $('.success-msg').text(response.message); }else if(response.errors) { $.each(response.errors, function(name, error){ error = '<small class="text-danger error mt-2">' + error + '</small>' $form.find('[name=' + name + ']').after(error); }) } }, cache: false, contentType: false, processData: false }); }); </script> </html> </html>Step 9: 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.pyfrom 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.pyfrom 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....