Django Custom Import Export example

Published On: 02/12/2022 | Category: Django


Hi Dev,

I will explain step by step tutorial django custom import export excel example. I explained simply step by step django custom import excel file. step by step explain django custom import export excel example csv. I explained simply step by step django custom import export excel to database example download. Let's see bellow example how to custom import export data in django.

The django-import-export library supports multiple formats, including xls, csv, json, yaml, and all other formats supported by tablib. It also have a Django admin integration, which is really convenient to use.

Here i explained simply step by step example of django custom import export excel example.

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 post names. 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: Installing Django-Import-Export Library

First of all we need to install django-import-export library simply run below command.

pip install django-import-export

Step 4: Update setting.py

Then update INSTALLED_APPS within our settings.py file to notify Django about the app.

settings.py
....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'import_export',

    'core',
]

IMPORT_EXPORT_USE_TRANSACTIONS = True

Step 5: Create Model and Resources

The django-import-export library operates on the Resource concept, which is a class definition similar to how Django handles model forms and admin classes.

core/models.py
class Employee(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=60)
    email = models.EmailField(blank=True)
    day_started = models.DateField()
    location = models.CharField(max_length=100, blank=True)

    def __str__(self):
        return self.first_name

Ok, all set. We can engender a migrations file for this change, then integrate it to our database via migrate.

python manage.py makemigrations
python manage.py migrate
core/resources.py
from import_export import resources
from .models import Employee

class EmployeeResource(resources.ModelResource):
    class Meta:
        model = Employee

Step 6: Creating the Views

In this step, we need to configure views open the core/views.py file and add:

core/views.py
from django.shortcuts import render
from django.http import HttpResponse
from tablib import Dataset

from .resources import EmployeeResource
from .models import Employee

def export_data(request):
    if request.method == 'POST':
        # Get selected option from form
        file_format = request.POST['file-format']
        employee_resource = EmployeeResource()
        dataset = employee_resource.export()
        if file_format == 'CSV':
            response = HttpResponse(dataset.csv, content_type='text/csv')
            response['Content-Disposition'] = 'attachment; filename="exported_data.csv"'
            return response        
        elif file_format == 'JSON':
            response = HttpResponse(dataset.json, content_type='application/json')
            response['Content-Disposition'] = 'attachment; filename="exported_data.json"'
            return response
        elif file_format == 'XLS (Excel)':
            response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel')
            response['Content-Disposition'] = 'attachment; filename="exported_data.xls"'
            return response   

    return render(request, 'export.html')

def import_data(request):
    if request.method == 'POST':
        file_format = request.POST['file-format']
        employee_resource = EmployeeResource()
        dataset = Dataset()
        new_employees = request.FILES['importData']

        if file_format == 'CSV':
            imported_data = dataset.load(new_employees.read().decode('utf-8'),format='csv')
            result = employee_resource.import_data(dataset, dry_run=True)                                                                 
        elif file_format == 'JSON':
            imported_data = dataset.load(new_employees.read().decode('utf-8'),format='json')
            # Testing data import
            result = employee_resource.import_data(dataset, dry_run=True) 

        if not result.has_errors():
            # Import now
            employee_resource.import_data(dataset, dry_run=False)

    return render(request, 'import.html')    

Step 7: Creating Templates

Next, then with your text editor create new templates files: core/import.html file and the add:

core/import.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Import</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/jquery.slim.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-9">
                <div class="card">
                    <div class="card-header">
                        <h4>Django Custom Import Export Example - <span class="text-primary">Tuts-Station.com</span></h4>
                    </div>
                    <div class="card-body">
                        <div class="col-md-12">
                            {% 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>
                        <form method="post" enctype="multipart/form-data">
                            {% csrf_token %}
                            <div class="col-md-12">
                                <div class="custom-file">
                                    <input type="file" name="importData" class="custom-file-input" id="customFile">
                                    <label class="custom-file-label" for="customFile">Choose file</label>
                                </div>
                            </div>
                            <div class="col-md-12 my-3">
                                <p class="m-0">Please select format of file.</p>
                                <select name="file-format" class="form-control">
                                    <option selected>Choose format...</option>
                                    <option>CSV</option>
                                    <option>JSON</option>
                                </select>
                            </div>
                            <div class="col-md-12">
                                <button class="btn btn-primary" type="submit">Import</button>
                                <a href="{% url 'export_data' %}" class="btn btn-success" >Go to Export</a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
<script type="text/javascript">
// Add the following code if you want the name of the file appear on select
$(".custom-file-input").on("change", function() {
  var fileName = $(this).val().split("\\").pop();
  $(this).siblings(".custom-file-label").addClass("selected").html(fileName);
});
</script>
</html>

Next, then with your text editor create new templates files: core/export.html file and the add:

core/export.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Export</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/jquery.slim.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-9">
                <div class="card">
                    <div class="card-header">
                        <h3>Django Custom Import Export Example - Tuts-Station.com</h3>
                    </div>
                    <div class="card-body">
                        <form method="post" enctype="multipart/form-data">
                            <p class="m-0">Please select format of file.</p>
                            <div class="row">
                                <div class="col-md-9">
                                    {% csrf_token %}
                                    <select name="file-format" class="form-control my-3">
                                        <option selected>Choose format...</option>
                                        <option>CSV</option>
                                        <option>JSON</option>
                                        <option>XLS (Excel)</option>
                                    </select>
                                </div>
                                <div class="col-md-3 mt-3 text-right">
                                    <button class="btn btn-primary" type="submit">Export</button>
                                </div>
                            </div>
                        </form>
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>Id</th>
                                    <th>First Name</th>
                                    <th>Last Name</th>
                                    <th>Email</th>
                                    <th>Day Started</th>
                                    <th>Location</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for employee in employees %}
                                    <tr>
                                        <td>{{ employee.id }}</td>
                                        <td>{{ employee.first_name }}</td>
                                        <td>{{ employee.last_name }}</td>
                                        <td>{{ employee.email }}</td>
                                        <td>{{ employee.day_started }}</td>
                                        <td>{{ employee.location }}</td>
                                    </tr>
                                {% endfor %}
                                <tr></tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Step 8: Import Data

Assume that we have file named employees.csv:

first_name,last_name,email,day_started,location
BHavesh,Sonagra,[email protected],2022-08-15,Rajkot,
Nik,Patel,[email protected],2022-07-05,Rajkot,

So, If you want to use import export in admin then simply add following code in your admin.py:

core/admin.py
from import_export.admin import ImportExportModelAdmin
from django.contrib import admin
from .models import Employee

@admin.register(Employee)
class EmployeeAdmin(ImportExportModelAdmin):
    pass

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.py
from django.urls import path
from . import views

urlpatterns = [
    path('export', views.export_data, name='export_data'),
    path('import', views.import_data, name='import_data'),
]

Next, we require to add a URL path for our example app 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

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

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
http://localhost:8000/import
http://localhost:8000/export
Import Page:

Export Page:

I hope it will help you....

Happy Coding!