Django Import Export Library

django-import-export library provides an import_export app for your Django project. You can use the import_export app with Django Admin. It will simply add fully functional import and export buttons to the admin dashboard.


Model data can be imported from CSV, XML, Excel, JSON, etc. You may also export data to multiple file formats like CSV, XLS, TSV, ODS, JSON, YAML, and HTML.

You may easily add the import_export app in 4 easy steps:

  • Step 1: Install django-import-export via pip
  • Step 2: Add import_export to INSTALLED_APPS in settings.py
  • Step 3: Import and inherit ImportExportModelAdmin in admin.py
  • Step 4: Set import_export app permissions under settings.py (if needed)


django import export


Installing django-import-export library

To install django-import-export library simply run:

pip install django-import-export


Add import_export app to the project settings.py

Now, you must add import_export app in your project settings.py under the INSTALLED_APPS attribute list. Notice that the "-" is replaced with "_" because of Python's nomenclature rules.

    INSTALLED_APPS = [
        ...
        'import_export',
    ]   


Sample Project of Django Import Export

[Note: Complete project is at the end of the page for free download.]

We are going to use an example model class called Blog under myapp

models.py

    from django.db import models                              
    class Blog(models.Model):
        title = models.CharField(max_length=120)
        author = models.CharField(max_length=120)
        date_of_publishing = models.DateField(auto_now_add=True)
        content = models.TextField()
        def __str__(self):
            return self.title           

Now, simply import and inherit ImportExportModelAdmin class in admin.py

admin.py

    from import_export.admin import ImportExportModelAdmin
    from django.contrib import admin
    from .models import Blog
    
    class BlogAdmin(ImportExportModelAdmin, admin.ModelAdmin):
        ...
        
    admin.site.register(Blog, BlogAdmin)  

Note: ImportExportModelAdmin should be prior to admin.ModelAdmin in the multiple inheritance sequence to avoid MRO (Method Resolution Order) error.


Importing

django import csvExporting

django export csv

Django import_export app permissions

With the above code, all staff users will have access to django import export feature under the Admin interface. In order to restrict access to users with add, view, change or delete permissions, add the code below in project settings.py.

IMPORT_EXPORT_IMPORT_PERMISSION_CODE = 'delete' 
IMPORT_EXPORT_EXPORT_PERMISSION_CODE = 'delete'

In place of delete, you may use other permissions like "add", "view" or "change".