I am not able to export image in CSV file in Django Admin
Everytime I export the data all of it gets exported but for the image which is there I am only getting the url of the image and not actual image. Image of exported CSV file
Database fields from where I export it
I want the actual image to be exported in CSV file and not the image storage path. If anyone knows how to do it kindly help.
To export an image in a CSV file from Django Admin, you will need to override the to_csv method of the ModelAdmin class for the model that has the image field.
Here is an example of how you could do this:
from django.http import HttpResponse
from django.utils.translation import gettext as _
from django.contrib import admin
class MyModelAdmin(admin.ModelAdmin):
def to_csv(self, request, queryset):
# Create a HttpResponse object with the appropriate CSV header
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=
{}.csv'.format(self.model._meta.verbose_name)
# Create a CSV writer
writer = csv.writer(response)
# Write the headers
headers = [field.name for field in self.model._meta.fields]
writer.writerow(headers)
# Write the rows
for obj in queryset:
# Get the image data
image_data = obj.image.file.read()
# Encode the image data as base64
image_data_base64 = base64.b64encode(image_data).decode()
# Write the row to the CSV file
writer.writerow([image_data_base64] + [getattr(obj, field) for
field in headers[1:]])
return response
to_csv.short_description = _("Export CSV")
# Register the model with the custom ModelAdmin class
admin.site.register(MyModel, MyModelAdmin)
This code defines a custom to_csv method for the MyModelAdmin class that exports the image data as a base64-encoded string. The image data is read from the image field of the model, which is assumed to be a FileField or a subclass. The base64-encoded image data is then added to the rows of...
I hope this helps!
You cannot save files in the database and you can only save the address where they are stored. But there is one way, and that is to convert the files to a base64 format and save them as a string or text.