Django's admin site, I found out that there are various plugins.
I wanted to import / export the data on the management screen in a format such as CSV, so When I looked it up, I could easily do it with django-import-export. A memorandum at that time.
First install with pip
$ pip install django-import-export
Added ʻimport_export` to INSTALLED_APPS
# settings.py
INSTALLED_APPS = (
...
'import_export',
)
Add settings for the target data.
The sample model looks like this.
# models.py
class Book(models.Model):
name = models.CharField('Book name', max_length=100)
author = models.CharField('Book name', max_length=100)
django-import-export settings.
Add a class that inherits ModelResource
for the target model.
It seems that setting related items will be written here.
# admin.py
from django.contrib import admin
from import_export import resources
from import_export.admin import ImportExportModelAdmin
from .models import Book
class BookResource(resources.ModelResource):
#Django for Model-import-export settings
class Meta:
model = Book
@admin.register(Book)
class BookAdmin(ImportExportModelAdmin):
#Use ImportExportModelAdmin
ordering = ['id']
list_display = ('id', 'title', 'author')
# django-import-exports settings
resource_class = BookResource
Finally, prepare an Admin class that inherits ImportExportModelAdmin,
If you set resource_class to a class that inherits ModelResource
, it's OK!
Then, the button is displayed like this. Easy (* ´ω ` *)
I thought I didn't need to import it separately, so I disabled it. It seems that only ʻExport Mixin` should be used.
# ...Abbreviation
from import_export.admin import ExportMixin
@admin.register(Book)
class BookAdmin(ExportMixin, admin.ModelAdmin):
#Admin to ExportMixin.OK if you add it to ModelAdmin
ordering = ['id']
list_display = ('id', 'title', 'author')
# django-import-exports settings
resource_class = BookResource
By default, you can choose JSON or YML, but CSV is all you need. I narrowed down the parts that can be selected. OK if you specify formats
# ...Abbreviation
from import_export.formats import base_formats
@admin.register(Book)
class BookAdmin(ImportExportModelAdmin):
ordering = ['id']
list_display = ('id', 'title', 'author')
# django-import-exports settings
resource_class = BookResource
formats = [base_formats.CSV] #Can be specified in formats
that's all!!
We have released "Tsundoku How Match", a reading management app for Tsundoku! Tsundoku How Match is developed with Nuxt.js + Firebase!
If you like, please play ヽ (= ´ ▽ `=) ノ
If you have any requests, impressions, advice, etc. To the official account (@MemoryLoverz) and the developer (@kira_puka) ♪
Recommended Posts