How to Import or Export Data from Django Admin?

How to Import or Export Data from Django Admin?

How to install django-import-export in a Django project?

If you have been using Django admin, you might have realized that there is no way that you can import to export some data from the Django admin panel in supported formats such as CSV, JSON or an Excel Spreadsheet etc.

Well, without wasting any time, let’s directly jump into the implementation of how to add import-export functionality in Django Admin for any model.

We will use a popular third-party library called django-import-export in this blog, you can find this library on PyPI.

Installation:

The simplest way to install django-import-export is to use pip.

pip install django-import-export

After the successful installation, you just need to add import_export package in your INSTALLED_APPS list of settings.py file.

# settings.py
...

INSTALLED_APPS = [
    ...
    'import_export',
]

...

Integration with Django Admin:

django-import-export comes with multiple admin classes and mixins to make it easy for you to integrate with any Django model.

If you want to integrate both Import and Export together in a model admin, you can import the ImportExportModelAdmin and register your model admin, here is the code:

# app_name/admin.py

from app_name.models import Book
from import_export.admin import ImportExportModelAdmin

@admin.register(Book)
class BookAdmin(ImportExportModelAdmin):
    ...

If you are looking to only integrate the Import or maybe only the export feature in your model admin, you can use the ImportMixin or ExportMixin respectively. But keep in mind that these mixins are combined with admin.ModelAdmin.

For only Import:

# app_name/admin.py

from django.contrib import admin
from app_name.models import Book
from import_export.admin import ImportMixin

@admin.register(Book)
class BookAdmin(ImportMixin, admin.ModelAdmin):
    ...

For only Export:

# app_name/admin.py

from django.contrib import admin
from app_name.models import Book
from import_export.admin import ExportMixin

@admin.register(Book)
class BookAdmin(ExportMixin, admin.ModelAdmin):
    ...

If you want to go into the depth of the django-import-export library, you can visit the Official GitHub repository or Official documentation.

Any thoughts? Write it down in the comments.

For more such crispy blogs daily, follow Dev.Junction, subscribe to our newsletter and get notified.

Did you find this article valuable?

Support Dev.Junction by becoming a sponsor. Any amount is appreciated!