Django-import-export: Import/export files and images

Created on 31 May 2014  路  6Comments  路  Source: django-import-export/django-import-export

Hello.

Sorry for dump question.

How to work with models that have file or imagefield?

stale

Most helpful comment

Just in case someone comes across this - this is the workaround that made it work for me:

class MemberResource(resources.ModelResource):
    class Meta:
        model = Member

    def __init__(self):
        super(MemberResource, self).__init__()
        # Introduce a class variable to pass dry_run into methods that do not get it
        self.in_dry_run = False

    def before_import(self, dataset, using_transactions, dry_run, **kwargs):
        # Set helper class method to dry_run value
        self.in_dry_run = dry_run

    def before_import_row(self, row, row_number=None, **kwargs):
        if not self.in_dry_run:
            # Get URL and split image name from import file
            image_url = row['portrait']
            image_name = image_url.split('/')[-1]

            # Generate temporary file and download image from provided URL
            tmp_file = NamedTemporaryFile(delete=True, dir=f'{settings.MEDIA_ROOT}')
            tmp_file.write(urllib.request.urlopen(image_url).read())
            tmp_file.flush()

            # Add file object to row
            row['portrait'] = File(tmp_file, image_name)

All 6 comments

Although there is no built in workflow for importing images and files, it should be easy enough to subclass fields or just use one of import hooks to handle saving images. Please check the documentation

Hello! Is someone already implement this? Can share a code?

I have done something like that but this is not the good solution because "after_import_row" is called twice (upload image 2 times). Someone have a solution?

from urllib.parse import urlparse
import os
import requests
from django.core.files.base import ContentFile

# Import image from url with django import export application
def save_image_from_row(instance, row):
    if row['image']:
        if row['image'] == instance.image:
            image_content = ContentFile(requests.get(row['image']).content)
            url_image = urlparse(row['image'])
            instance.image.save(os.path.basename(url_image.path), image_content)
            instance.save()

--------------------------------------------------------------------

class CatLivreAuthorResource(resources.ModelResource):
    class Meta:
        model = CatLivreAuthor
        fields = ('id', 'first_name', 'last_name', 'copyright', 'image')

    def after_import_row(self, row, row_result, **kwargs):
            instance = CatLivreAuthor.objects.get(id=row['id'])
            save_image_from_row(instance, row)

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

How about exporting an image into the XLSx?

Just in case someone comes across this - this is the workaround that made it work for me:

class MemberResource(resources.ModelResource):
    class Meta:
        model = Member

    def __init__(self):
        super(MemberResource, self).__init__()
        # Introduce a class variable to pass dry_run into methods that do not get it
        self.in_dry_run = False

    def before_import(self, dataset, using_transactions, dry_run, **kwargs):
        # Set helper class method to dry_run value
        self.in_dry_run = dry_run

    def before_import_row(self, row, row_number=None, **kwargs):
        if not self.in_dry_run:
            # Get URL and split image name from import file
            image_url = row['portrait']
            image_name = image_url.split('/')[-1]

            # Generate temporary file and download image from provided URL
            tmp_file = NamedTemporaryFile(delete=True, dir=f'{settings.MEDIA_ROOT}')
            tmp_file.write(urllib.request.urlopen(image_url).read())
            tmp_file.flush()

            # Add file object to row
            row['portrait'] = File(tmp_file, image_name)
Was this page helpful?
0 / 5 - 0 ratings