Django import_export data

You can import data in django models from csv, xml, excel, json etc. You may also export data into multiple formats like csv, xls, xlsx, tsv, ods, json, yaml and html.

django import export

django-import-export library

To install django-import-export library simply run:

pip install django-import-export

Now you must add import_export app in project settings.py

    INSTALLED_APPS = [
        ...
        'import_export',
    ]
                                

Example Project

We are going to use an example model class called Blog.

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
                                

django-import-export in Admin interface

Simply import and inherit ImportExportModelAdmin class.

from import_export.admin import ImportExportModelAdmin

admin.py

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

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

django export csv

Django import export permissions

With above code all staff users will have access to django import export feature under Admin interface. In order to restrict access to user 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".