Registry / web-framework / django-import-export

django-import-export

JSON →
library4.4.1pypypi✓ verified 25d ago

django-import-export is a versatile Django application and library for importing and exporting data, with seamless integration into the Django admin interface. It supports various data formats like CSV, JSON, and Excel, and allows for robust customization through `Resource` classes for complex data mapping and transformations. The project maintains active development with regular patch releases and significant updates approximately once a year.

pip install django-import-export
INSTALL
IMPORT
SIG · DJANGO-IMPORT-EXPO
D
django-import-export
web-frameworkpythonv4.4.1
Install
6.8s avg
Import
625ms
Disk
68MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v4.4.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.910 runs
installs and imports cleanly · install 0.0s · import 0.655s · 68.2MB
glibc
py 3.103.910 runs
installs and imports cleanly · install 6.8s · import 0.595s · 69MB
68MB installed
● package 68MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

ModelResource
from import_export.resources import ModelResource
Field
from import_export.fields import Field
ForeignKeyWidget
from import_export.widgets import ForeignKeyWidget
ImportExportModelAdmin
from import_export.admin import ImportExportModelAdmin

This quickstart demonstrates how to define a `ModelResource` for a Django model and perform a programmatic export. It includes a minimal Django setup to make the example runnable independently, showing how to handle related `ForeignKey` fields using `ForeignKeyWidget` for clear human-readable mapping during export and import.

import os import django from django.conf import settings from import_export import resources from import_export.fields import Field from import_export.widgets import ForeignKeyWidget # Minimal Django setup for standalone script if not settings.configured: settings.configure( INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.admin', 'import_export', 'my_app', # Placeholder for your app ], DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}}, DEBUG=True, USE_TZ=True, TIME_ZONE='UTC', SECRET_KEY=os.environ.get('DJANGO_SECRET_KEY', 'super-secret-key-for-testing'), TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, }], ROOT_URLCONF='django_import_export.urls', # Dummy URLconf required by django.setup() ) django.setup() from django.db import models # 1. Define your Django Models (example) class Category(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name class Meta: app_label = 'my_app' class Product(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return self.name class Meta: app_label = 'my_app' # Need to create tables for these models in the in-memory DB for the example from django.db import connection with connection.schema_editor() as schema_editor: schema_editor.create_model(Category) schema_editor.create_model(Product) # 2. Define a Resource for your Model class ProductResource(resources.ModelResource): category = Field( column_name='category_name', attribute='category', widget=ForeignKeyWidget(Category, 'name') # Match category by name during import/export ) class Meta: model = Product fields = ('id', 'name', 'price', 'category',) # Fields to include export_order = ('id', 'name', 'price', 'category',) # Order for export # 3. Use the Resource to export data programmatically category_electronics = Category.objects.create(name='Electronics') Product.objects.create(name='Laptop', price=1200.00, category=category_electronics) Product.objects.create(name='Mouse', price=25.00, category=category_electronics) product_resource = ProductResource() dataset = product_resource.export() print("\n--- Exported CSV data ---") print(dataset.csv)
Debug
Known issues
breakingVersion 4.0.0 introduced significant breaking changes: `base_queryset` was removed (use `get_queryset`), `export_order` default changed, and `fields`, `exclude`, `widgets` behavior was refined. Additionally, Python < 3.9 and Django < 3.2 are no longer supported.
fix
Review the official changelog for v4.0.0. Update `base_queryset` to `get_queryset`. Adjust `fields`, `exclude`, `widgets` definitions if relying on previous implicit behaviors. Ensure Python and Django versions meet new requirements.
affects: >=4.0.0
breakingIn v4.0.0, the `import_obj` and `save_row` methods now return a tuple `(obj, new)` to indicate if a new object was created. Also, `get_data_for_export` was renamed to `get_export_data`.
fix
Update custom `import_obj` and `save_row` implementations to handle the `(obj, new)` return signature. Rename any overrides of `get_data_for_export` to `get_export_data`.
affects: >=4.0.0
gotchaWhen dealing with `ForeignKey` or `ManyToMany` fields, you must explicitly define a `Field` with a `ForeignKeyWidget` or `ManyToManyWidget` and specify the `field` argument (e.g., `'name'`, `'slug'`). Otherwise, the library will attempt to match by primary key (ID) during import, which is often not desired.
fix
For related fields, use `Field(attribute='related_field', widget=ForeignKeyWidget(RelatedModel, 'unique_field_name'))` or `ManyToManyWidget`.
affects: All
gotchaImporting or exporting very large datasets can lead to memory exhaustion. By default, `queryset` fetching might load all objects into memory.
fix
For export, override `get_queryset` in your `Resource` to add `.iterator()`: `return super().get_queryset().iterator()`. For import, consider processing data in chunks or pre-processing the file to reduce memory footprint. Always use `dry_run` before final imports.
affects: All
deprecatedSince v3.0.0, `ImportExportMixin` and `ImportExportModelAdmin` strictly require the `resource_class` attribute to be explicitly set. Inferring the `Resource` from `_meta.model` is no longer supported.
fix
Always set `resource_class = YourResource` in your `ModelAdmin` class inheriting from `ImportExportModelAdmin`.
affects: >=3.0.0
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'import_export'
The `django-import-export` library is either not installed, or has not been added to your Django project's `INSTALLED_APPS` in `settings.py`.
fix
Ensure the package is installed with `pip install django-import-export` and then add `'import_export'` to your `INSTALLED_APPS` list in `settings.py`.
KeyError: 'id' in get_import_id_fields()
This error, or similar messages like 'The following fields are declared in 'import_id_fields' but are not present in the resource,' indicates that the `Resource` class cannot find a field it expects to uniquely identify instances during the import process.
fix
Configure the `Meta.import_id_fields` in your `Resource` class to correctly match a field (or fields) present in your import data and your model, or explicitly include the 'id' field if it's expected and missing.
AttributeError: 'str' object has no attribute 'year'
This error typically occurs when importing data containing date or datetime fields that are not in a format parsable by the default `DateFieldWidget` or `DateTimeFieldWidget`, or when an empty string is provided to a field expecting a date object.
fix
Ensure your date/datetime columns in the import file are in a consistent and recognizable format (e.g., YYYY-MM-DD). If custom formats are needed, define a custom `Widget` for the field in your `Resource` class to handle the specific date parsing.
AttributeError: 'str' object has no attribute 'objects'
This error occurs when a model is referenced as a string (e.g., from `settings.AUTH_USER_MODEL`) within a `ForeignKeyWidget` or other `django-import-export` context, but the system expects an actual model class to access its manager (`.objects`).
fix
Resolve the model string to its actual class using `django.apps.apps.get_model()` or `django.contrib.auth.get_user_model()` (for the user model) before passing it to the `ForeignKeyWidget`.
Foreign key is null when importing
This issue arises when importing data with foreign key relationships where the related object cannot be found or correctly linked from the import data, often due to not using a `ForeignKeyWidget` or providing insufficient/incorrect lookup values.
fix
Use a `ForeignKeyWidget` for foreign key fields in your `Resource` to specify how to look up related instances. For example, `ForeignKeyWidget(RelatedModel, 'field_to_lookup')` where `field_to_lookup` is a unique identifier in the related model.
Upgrade
Version history
4.4.1latest on PyPI · released May 5, 2026
Audit
Dependencies
djangorequiredCore framework requirement, as it is a Django application.
tablibrequiredBackend for data handling, format conversions.
openpyxlrequiredRequired for Excel (.xlsx) file support.
pandasoptionalOptional dependency for advanced data manipulation and reading/writing certain formats.
Agent activity
12 hits · last 30 days
node
10
OpenAI (training)
1
Resources
django-import-export — pip install django-import-export · libregistry