I have a django app I am working on and in the admin page, I'd like to be able to export a model's list view as csv, xls and multiple other file formats. I'm using django-import-export
package for that. I have installed and added it to my installed apps in settings.py.
In my models.py
I have..
class Student(models.Model):
firstname = models.CharField(max_length=20)
middlename = models.CharField(max_length=20)
lastname = models.CharField(max_length=20)
admission_number = models.CharField(max_length=10)
grade = models.CharField(max_length=10)
joined = models.DateField(auto_now_add=True)
def __str__(self):
return f'{self.firstname} {self.lastname}'
My admin.py
file
class StudentAdmin(admin.ModelAdmin):
list_display = ('firstname', 'lastname', 'admission_number', 'grade', 'joined')
list_filter = ('grade', 'joined',)
admin.site.register(Student, StudentAdmin)
To handle the import and export functionality, I have created a file in the same directory called resource.py where I have the following django-import-export
specific code.
from import_export import resources
from import_exports.fields import Field
from .models import Student
class StudentResource(resources.ModelResource):
full_name = Field(column_name='name')
class Meta:
model = Student
fields = ('full_name', 'admission_number', 'grade', 'joined')
widgets = {
'joined': { 'format': '%d/%m/%Y'},
}
def dehydrate_full_name(self, student):
return f'{student.firstname} {student.middlename} {student.lastname}'
As you can see from the above code, I have created a new field full_name
which I want to hold the full name of a student under the column name
and I'd like it exported that way.
I would like to be able to export the data via an admin action and after reading through django-import-export documentation, I updated my admin.py file..
# Added these imports
from import_export.admin import ImportExportActionModelAdmin
from .resource import StudentResource
class StudentExportAdmin(ImportExportActionModelAdmin):
resource_class = StudentResource
class StudentAdmin(admin.ModelAdmin):
list_display = ('firstname', 'lastname', 'admission_number', 'grade', 'joined')
list_filter = ('grade', 'joined',)
admin.site.register(Student, StudentAdmin)
admin.site.register(StudentExportAdmin)
What am I doing wrong here? Someone please help.
change according to this,
class StudentAdmin(ImportExportActionModelAdmin):
resource_class = StudentResource
list_display = ('firstname', 'lastname', 'admission_number', 'grade', 'joined')
list_filter = ('grade', 'joined',)
admin.site.register(Student,StudentAdmin)
remove this line, as import-export
will automatically place it in the admin
panel according to the resources
you have used.