import_id_fields
error on import
The following error message can be seen on import:
The following fields are declared in ‘import_id_fields’ but are not present in the resource
This indicates that the Resource has not been configured correctly, and the import logic fails. Specifically, the import process is attempting to use either the defined or default values for import_id_fields
and no matching field has been detected in the resource fields. See Create or update model instances.
In cases where you are deliberately using generated fields in import_id_fields
and these fields are not present in the dataset, then you need to modify the resource definition to accommodate this. See Using ‘dynamic fields’ to identify existing instances.
This issue can apply if you have implemented post-save Signals, and you are using the import workflow in the Admin interface. You will find that the post-save signal is called twice for each instance. The reason for this is that the model save()
method is called twice: once for the ‘confirm’ step and once for the ‘import’ step. The call to save()
during the ‘confirm’ step is necessary to prove that the object will be saved successfully, or to report any exceptions in the Admin UI if save failed. After the ‘confirm’ step, the database transaction is rolled back so that no changes are persisted.
Therefore there is no way at present to stop save()
being called twice, and there will always be two signal calls. There is a workaround, which is to set a temporary flag on the instance being saved:
class BookResource(resources.ModelResource): def before_save_instance(self, instance, row, **kwargs): # during 'confirm' step, dry_run is True instance.dry_run = kwargs.get("dry_run", False) class Meta: model = Book fields = ('id', 'name')
Your signal receiver can then include conditional logic to handle this flag:
@receiver(post_save, sender=Book) def my_callback(sender, **kwargs): instance = kwargs["instance"] if getattr(instance, "dry_run"): # no-op if this is the 'confirm' step return else: # your custom logic here # this will be executed only on the 'import' step pass
Further discussion here and here.
How to dynamically set resource valuesThere can be use cases where you need a runtime or user supplied value to be passed to a Resource. See How to dynamically set resource values.
How to set a value on all imported instances prior to persistingIf you need to set the same value on each instance created during import then refer to How to set a value on all imported instances prior to persisting.
How to export from more than one tableIn the usual configuration, a Resource
maps to a single model. If you want to export data associated with relations to that model, then these values can be defined in the fields
declaration. See Model relations.
Please refer to this issue.
How to hide stack trace in UI error messagesPlease refer to How to format UI error messages.
Ids incremented twice during importWhen importing using the Admin site, it can be that the ids of the imported instances are different from those show in the preview step. This occurs because the rows are imported during ‘confirm’, and then the transaction is rolled back prior to the confirm step. Database implementations mean that sequence numbers may not be reused.
Consider enabling IMPORT_EXPORT_SKIP_ADMIN_CONFIRM as a workaround.
See this issue for more detailed discussion.
Not Null constraint fails when importing blank CharFieldThis was an issue in v3 which is resolved in v4. The issue arises when importing from Excel because empty cells are converted to None
during import. If the import process attempted to save a null value then a ‘NOT NULL’ exception was raised.
In v4, initialization checks to see if the Django CharField
has blank set to True
. If it does, then null values or empty strings are persisted as empty strings.
If it is necessary to persist None
instead of an empty string, then the allow_blank
widget parameter can be set:
class BookResource(resources.ModelResource): name = Field(widget=CharWidget(allow_blank=False)) class Meta: model = Book
See this issue.
Foreign key is null when importingIt is possible to reference model relations by defining a field with the double underscore syntax. For example:
fields = ("author__name")
This means that during export, the relation will be followed and the referenced field will be added correctly to the export.
This does not work during import because the reference may not be enough to identify the correct relation instance. ForeignKeyWidget
should be used during import. See the documentation explaining Foreign Key relations.
See the following responses on StackOverflow:
How to customize Excel export data
If you want more control over how export data is formatted when exporting to Excel you can write a custom format which uses the openpyxl API. See the example here.
How to set export file encodingIf export produces garbled or unexpected output, you may need to set the export encoding. See this issue.
How to create relation during import if it does not existSee Creating non-existent relations.
How to handle large file importsIf uploading large files, you may encounter time-outs. See Using celery and Bulk imports.
Performance issues or unexpected behavior during importThis could be due to hidden rows in Excel files. Hidden rows can be excluded using IMPORT_EXPORT_IMPORT_IGNORE_BLANK_LINES.
Refer to this PR for more information.
How to use field other than id in Foreign Key lookup ‘failed to assign change_list_template attribute’ warning in logsThis indicates that the change_list_template attribute could not be set, most likely due to a clash with a third party library. Refer to Interoperability with 3rd party libraries.
How to skip rows with validation errors during importRefer to this comment.
FileNotFoundError
during Admin import ‘confirm’ step
You may receive an error during import such as:
FileNotFoundError [Errno 2] No such file or directory: '/tmp/tmp5abcdef'
This usually happens because you are running the Admin site in a multi server or container environment. During import, the import file has to be stored temporarily and then retrieved for storage after confirmation. Therefore FileNotFoundError
error can occur because the temp storage is not available to the server process after confirmation.
To resolve this, you should avoid using temporary file system storage in multi server environments.
Refer to Import confirmation for more information.
How to export large datasetsLarge datasets can be exported in a number of ways, depending on data size and preferences.
You can write custom scripts or Admin commands to handle the export. Output can be written to a local filesystem, cloud bucket, network storage etc. Refer to the documentation on exporting programmatically.
You can use the third party library django-import-export-celery to handle long-running exports.
You can enable export via admin action and then select items for export page by page in the Admin UI. This will work if you have a relatively small number of pages and can handle export to multiple files. This method is suitable as a one-off or as a simple way to export large datasets via the Admin UI.
If you want to modify the names of the columns on export, you can do so by overriding get_export_headers()
:
class BookResource(ModelResource): def get_export_headers(self, fields=None): headers = super().get_export_headers(fields=fields) for i, h in enumerate(headers): if h == 'name': headers[i] = "NEW COLUMN NAME" return headers class Meta: model = BookHow to configure logging
Refer to logging configuration for more information.
Export to Excel givesIllegalCharacterError
This occurs when your data contains a character which cannot be rendered in Excel. You can configure import-export to sanitize these characters.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4