Giter VIP home page Giter VIP logo

Comments (10)

Smosker avatar Smosker commented on May 14, 2024 3

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

from django-import-export.

thetractor avatar thetractor commented on May 14, 2024 3

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)

from django-import-export.

DayDotMe avatar DayDotMe commented on May 14, 2024 2

Just in case someone comes across this - here is a custom format to process embedded images in a XLSX file, using openpyxl_image_loader.


class XLSXWithPicture(XLSX):
    def create_dataset(self, in_stream):
        """
        Create dataset from first sheet.
        """
        from io import BytesIO

        import openpyxl

        xlsx_book = openpyxl.load_workbook(BytesIO(in_stream))
        sheet = xlsx_book.active
        image_loader = SheetImageLoader(sheet)

        dataset = tablib.Dataset()
        # obtain generator
        rows = sheet.rows
        dataset.headers = [cell.value for cell in next(rows)]

        for row in rows:
            row_values = []
            for cell in row:
                if image_loader.image_in(cell.coordinate):
                    image = image_loader.get(cell.coordinate)
                    buffer = io.BytesIO()
                    image.save(buffer, format=image.format)
                    row_values.append(buffer.getvalue())
                else:
                    row_values.append(cell.value)
            dataset.append(row_values)
        return dataset

class SomeModelResource(resources.ModelResource):
    logo = Field(column_name="logo", attribute="logo")

    class Meta:
        model = SomeModel

    def __init__(self):
        super().__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):
        """Hook to ensure ContentFile is not created during validation run"""
        logo = row.get("logo")
        if logo:
            if self.in_dry_run:
                row["picture"] = f"Image {row_number}"
            else:
                row["picture"] = ContentFile(logo, str(uuid.uuid4()))
                
class SomeModelImport(ImportExportModelAdmin):
    resource_class = SomeModelResource
    formats = [XLSXWithPicture]
       

from django-import-export.

DayDotMe avatar DayDotMe commented on May 14, 2024 1

@joserramintral check my updated answer

from django-import-export.

bmihelac avatar bmihelac commented on May 14, 2024

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

from django-import-export.

attilach avatar attilach commented on May 14, 2024

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)

from django-import-export.

stale avatar stale commented on May 14, 2024

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.

from django-import-export.

striveforbest avatar striveforbest commented on May 14, 2024

How about exporting an image into the XLSx?

from django-import-export.

joserramintral avatar joserramintral commented on May 14, 2024

That is exactly what i am looking for, thanks @DayDotMe !
Could you please share where you have included the code?
Thank you so much!

from django-import-export.

joserramintral avatar joserramintral commented on May 14, 2024

Thank you very much!!

from django-import-export.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.