Comments (10)
Hello! Is someone already implement this? Can share a code?
from django-import-export.
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.
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.
@joserramintral check my updated answer
from django-import-export.
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.
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.
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.
How about exporting an image into the XLSx?
from django-import-export.
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.
Thank you very much!!
from django-import-export.
Related Issues (20)
- Remove support for django3.2
- Add type hints HOT 3
- Confirmation page displays incorrect fields
- Using a ManyToManyWidget does not allow to ignore an empty value HOT 1
- A way to make a header column required HOT 4
- Add support for PositiveBigIntegerField HOT 2
- Python object as JSONWidget input HOT 3
- Admin Export fails for models with a primary key which is not "id" HOT 1
- Admin Export does not honour the "IMPORT_EXPORT_SKIP_ADMIN_ACTION_EXPORT_UI" setting HOT 1
- Badly formed header presents a stack trace instead of an error
- 4.0 compatiblity with AutoSlugField - unexpected keyword argument 'allow_blank' HOT 1
- Admin export confirm page runs a query for the entire table HOT 4
- attribute and column_name mixed up for export and Meta.fields HOT 3
- ImportForm does not support widgets with associated CSS and JS media
- Widget.__init__() got an unexpected keyword argument 'key_is_id' when a field is ForeignKey subclass HOT 2
- 'import_id_fields = []' can't handle programmaticaly created columns in 4.0 HOT 5
- Can't import file without an `id` column in V4 HOT 4
- v4 add custom delimiter for csv. HOT 5
- Referencing a column alias in the `fields` list causes a crash on import HOT 1
- `use_natural_foreign_keys` in ModelResource.Meta not working in V4 HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from django-import-export.