The whole corporate world is powered by spreadsheets.

Spreadsheets are the most popular way of bulk import and updating data.

Luckily, we have a great package called django-import-export which makes it super easy to enabled CSV, XLS, etc import export for our models in the admin site.

Install the package

pip install django-import-export

and add it to "requirements.txt":

django-import-export==3.2.0

Add it to your INSTALLED_APPS:

# settings.py

INSTALLED_APPS = [
    ...
    'import_export',

]

Documentation says you also need to run python manage.py collectstatic in order for it to work.

In the myapp/admin.py add two imports and add a resource for our import & export operations.

Since we are using other mixin for our ProductAdmin let's keep being consistent and add ImportExportMixin from import_export package instead of the ImportExportModelAdmin.

# admin.py

from import_export import resources  
from import_export.admin import ImportExportMixin

...


class ProductResource(resources.ModelResource):
    class Meta:
        model = Product
        fields = ('name', 'slug', 'is_active', 'id',)


class ProductAdmin(ImportExportMixin, DjangoQLSearchMixin, admin.ModelAdmin):
    prepopulated_fields = {'slug': ('name',)}
    list_display = ('name', 'slug', 'is_active', 'id',)
    filter_horizontal = ('category',)
    search_fields = ('name',)
    list_filter = ('category', 'is_active',)
    resource_classes = (ProductResource,)

Now in our we see two buttons added in our Django Admin Site change list: Import and Export

image

If we click on the "Import" button we'll see this form where they hint you which fields are expected, file to import and format.

image

CSV export for model in Django Admin Site

If we click on the "Export" button we see the export form with only format selection

image Exported file looks like this:

image

The list of objects that will get exported depends on filters and search queries in the change list. So which queryset is used to display objects will be also used for the export.

To demonstrate that I have set is_active=False for a couple of products and searched by is_active=False

image

And in the export we get only inactive products.

image

CSV Import and update in Django Admin site

Let's now change some product names and import this file back

I have changed names of both products, leaving the rest as is in this XLS file.

image

Going back to the change list, clicking export and in the import form I am selecting the file to import and XLS format, then submit.

image

I get a confirmation step where the difference with the existing data is shown.

image

Click "Confirm Import" and see that our data has indeed changed!

image