Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23247

Django Admin Import Error: NOT NULL Constraint Failed for ForeignKey Field in CSV Import

$
0
0

I'm experiencing a persistent issue with importing CSV data into my Django project using the django-import-export library in the admin panel. When trying to import records for a Copy model which has ForeignKey relations, I keep encountering a NOT NULL constraint failed error for the book_id field. AGAIN THIS ONLY OCCURS IN THE ADMIN PANEL, I have tested in shell and it works. I am sure there is no issue with the CSV and likely not even the resources/models files. It seems something is going wrong with the admin logic before the actual import.

Error looks like this but for every single row. It occurs when hitting "submit". I never even get to "Confirm Import" button

Line number: 1 - NOT NULL constraint failed: catalog_copy.book_idLine number: 2 - NOT NULL constraint failed: catalog_copy.book_idLine number: 3 - NOT NULL constraint failed: catalog_copy.book_idLine number: 4 - NOT NULL constraint failed: catalog_copy.book_idLine number: 5 - NOT NULL constraint failed: catalog_copy.book_idLine number: 6 - NOT NULL constraint failed: catalog_copy.book_idLine number: 7 - NOT NULL constraint failed: catalog_copy.book_idLine number: 8 - NOT NULL constraint failed: catalog_copy.book_idLine number: 9 - NOT NULL constraint failed: catalog_copy.book_idLine number: 10 - NOT NULL constraint failed: catalog_copy.book_id

Here are the relevant parts of my code:

models.py

from django.db import modelsfrom django.core.exceptions import ValidationErrorclass Book(models.Model):    title = models.CharField(max_length=200)    author = models.CharField(max_length=100)    isbn = models.CharField(max_length=13)class Format(models.Model):    name = models.CharField(max_length=100)class Copy(models.Model):    book = models.ForeignKey(Book, related_name='copies', on_delete=models.CASCADE)    format = models.ForeignKey(Format, related_name='copies', on_delete=models.CASCADE)    location = models.CharField(max_length=100)    is_available = models.BooleanField(default=True)

resources.py

from import_export import resourcesfrom .models import Copyclass CopyResource(resources.ModelResource):    class Meta:        model = Copy        fields = ('id', 'book', 'format', 'location', 'is_available')        import_id_fields = ['id']    def before_import_row(self, row, **kwargs):        book_title = row.get('Book Title')        isbn = row.get('ISBN')        author = row.get('Author')        format_name = row.get('Format')        book, created = Book.objects.get_or_create(            title=book_title,            defaults={'isbn': isbn, 'author': author}        )        format, created = Format.objects.get_or_create(            name=format_name        )        row['book'] = book.pk        row['format'] = format.pk

admin.py

from django.contrib import adminfrom import_export.admin import ImportExportModelAdminfrom .models import Copyfrom .resources import CopyResourceclass CopyAdmin(ImportExportModelAdmin):    resource_class = CopyResourceadmin.site.register(Copy, CopyAdmin)

I've manually verified the CSV and even tested uploading in the django shell which worked properly. But admin panel still does not work!!!

        import tablib   ...: from catalog.resources import CopyResource   ...:    ...: with open('library_copies.csv', 'r', encoding='utf-8') as f:   ...:     data = tablib.Dataset().load(f.read(), format='csv')   ...:    ...: resource = CopyResource()   ...: result = resource.import_data(data, dry_run=False)   ...:    ...: if result.has_errors():   ...:     print("Errors occurred during the import:")   ...:     for error in result.base_errors:   ...:         print(f"Base error: {error.error}")   ...: else:   ...:     print("The import would proceed without errors.")```The above succeeds but import through admin panel always has NOT NULL error

Viewing all articles
Browse latest Browse all 23247

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>