In this article, we will see how to export model data in .csv format. Sometimes, you might need to export your model data in different formats such as .csv or json or .xlsx for further work or reporting. You can do this by making some sort of script but I have a better way to do that.
Create a Django project and add an App. Setup urls and do some basic stuff like adding app in INSTALLED_APPS.
Create a model. Here, we don't have much to do with views.py, urls.py or any html file.
We only have work with settings.py, admin.py, models.py and admin urlpoint.
Example
Install the package −
pip install django-import-export
In settings.py −
INSTALLED_APPS += ['import_export']
Add this library as an app in your project.
Create a model −
class StudentData(models.Model): name=models.CharField(max_length=100) standard=models.CharField(max_length=100) section=models.CharField(max_length=100)
Here, we created a dummy model for testing
In admin.py −
from django.contrib import admin from .models import StudentData from import_export import resources from import_export.admin import ImportExportModelAdmin class StudentResource(resources.ModelResource): class Meta: model = StudentData class StudentAdmin(ImportExportModelAdmin): resource_class = StudentResource admin.site.register(StudentData,StudentAdmin)
Create an admin class for this ImportExportModel admin and register it to show it on the admin panel.
Output
Now, go to https://127.0.0.1/admin
Now, you can export data after clicking the 'Export' button.