Use import_export django library to import personnalized export CSV
I have two action in my application. First I export data to CSV using specific resources (see below) to have personalized Headers and Name of specific foreign Key instead Id. It's OK for Export CSV file. For Import this after modification ... An error raises : **Integrity Error: (1048, "Column 'produit_id' cannot be null") **
Below is the Resource Class for Greffons to get specific columns name and ordering columns in Meta.
class GreffonResource(resources.ModelResource):
comm = fields.Field(
column_name='Pre-Commandes',
attribute='comm',
)
greffons = fields.Field(
column_name='Greffons',
attribute='greffons',
)
objectif = fields.Field(
column_name='Objectifs',
attribute='objectif',
)
realise = fields.Field(
column_name='Realises',
attribute='realise',
)
reussi = fields.Field(
column_name='Reussis',
attribute='reussi',
)
produit = fields.Field(
column_name='Produits',
attribute='produit',
widget=widgets.ForeignKeyWidget(Produit, 'nom')
)
rang = fields.Field(
column_name='Rangs',
attribute='rang',
)
class Meta:
model = Greffons
fields = ('id', 'produit', 'comm', 'greffons', 'objectif', 'realise', 'reussi', 'rang')
export_order = ['id', 'produit', 'comm', 'greffons', 'objectif', 'realise', 'reussi', 'rang']
import_id_fields = ('id',)
After Export CSV file, I change data inside and import it after but error :( Below is the code to import data after POST.
produit_resource = GreffonResource()
dataset = Dataset()
new_datas = request.FILES['myfile']
imported_data = dataset.load(new_datas.read().decode(), format='csv')
if categorie == "GREFFONS":
result = produit_resource.import_data(imported_data, dry_run=True, raise_errors=True)
Most likely, you have a Produits.nom
value in your csv which does not map to a single existing Produit
instance. This is causing a create with a null value which fails.
You need to look at your import file and check all values of the 'Produits' column. Ensure that any value in there can map to a nom
entry in the Produit
table. Could it be that there are empty values for 'nom' which are being interpreted as null?
This line declares that your csv column called 'Produits' will have a value which maps to Produit.nom
:
produit = fields.Field(
column_name='Produits',
attribute='produit',
widget=widgets.ForeignKeyWidget(Produit, 'nom')
)
If you cannot find the source of the problem, the best thing is to step through the import with a debugger and you should see exactly what the issue is.