Export data from Django Admin to CSV

paul_freeman

Paul

Posted on July 1, 2024

Export data from Django Admin to CSV

Viewing all your data from your django Admin is not ideal, Sometimes, you may want to export it to a spreedsheet format and perform data analytics or validation.

This is where the django-import-export library comes in handy. It provides an easy way to import and export data in various formats, such as CSV, xlsx and more.

The focus of this tutorial will be on exporting data, and adding export button on admin.

Getting started with Django import export

Start by installing django-import export



pip install django-import-export


Enter fullscreen mode Exit fullscreen mode

Add it to installed apps



# settings.py
INSTALLED_APPS = [
    ...
    'import_export',
]


Enter fullscreen mode Exit fullscreen mode

Create a resource class inside your resource.py inside your app.



class SampleResource(resources.ModelResource):

    class Meta:
        model = SampleModel
        fields = ('id', 'price', 'description') # optional, only specified fields gets exported, else all the fields
        export_order = ('id', 'description', 'price') # optional, describes how order of export



Enter fullscreen mode Exit fullscreen mode

This class defines how the data will be imported and exported. You can also specify fields.

Now add it to admin so go to your admin.py



from django.contrib import admin
from import_export.admin import ExportMixin
from .models import MyModel
from .resources import MyModelResource

@admin.register(MyModel)
class MyModelAdmin(ExportMixin, admin.ModelAdmin):
    resource_class = MyModelResource


Enter fullscreen mode Exit fullscreen mode

That's it now you can export data directly from admin panel.

export button

Choose the fields to export
choose the fields

You can also customize like specifying permissions and more. You can read this in their docs

💖 💪 🙅 🚩
paul_freeman
Paul

Posted on July 1, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related