[Django] Import and export DB tables in Excel or CSV format

What to implement

  1. Add the following button to the administrator screen. --Import --Export
  2. Control the display with the authority of the DB table. --Import: Write permission required --Export: Anyone is OK

These are achieved with a library called django-import-export. This is a summary article on how to use django-import-export (introduction method).

Privileged account

This time, I created an account with the following privileges.

--admin: full privileges --guest: View permission only

Screen display

When logged in as admin

image.png←このボタンが追加される image.png

When logged in as guest

image.png←このボタンが追加される

image.png

Import screen

The format is as follows. Abundant. image.png

Export screen

The format is as follows. Even more abundant than imports. image.png

Implementation

Installation

django-import-export https://django-import-export.readthedocs.io/en/latest/

pip install django-import-export

Write in setting.py

setting.py


#Installed app
INSTALLED_APPS = (
    ...
    'import_export',
)

#Set that the import function on the management site requires permission
IMPORT_EXPORT_IMPORT_PERMISSION_CODE = 'change'

Static file export

python manage.py collectstatic

Write in admin.py

Assuming there is a table named Book in model.py

admin.py


from django.contrib import admin
from import_export import resources
from import_export.admin import ImportExportModelAdmin
from .models import *


#resource
class BookResource(resources.ModelResource):
    class Meta:
        model = Book

#management
class BookAdmin(ImportExportModelAdmin):
    resource_class = BookResource

#Registration
admin.site.register(Book, BookAdmin)

one thing

Simple and highly functional! Great. This time, all files were exported, but it seems that you can also filter. I want to challenge.

Recommended Posts

[Django] Import and export DB tables in Excel or CSV format
Excel, csv import, export with Django
Export Amazon RDS tables in CSV format
Export DB data in json format
Save TOPIX time series in pickle, csv, Excel format
How to convert Json file to CSV format or EXCEL format
Format the Git log and get the committed file name in csv format
Export and output files in Python