简体   繁体   中英

How to import auth.User on django-import/export

I can't import a CSV file into model on Django. I made a column 'author' and put the superuser's id which I am login to the admin site. But there was an error like this when I import the CSV file.

Line number: 1 - null value in column "author_id" violates not-null constraint DETAIL: Failing row contains (10, abc, blahblah, null, ).
5, abc, blahblah, , nah,wha,blah

csv file

author,title,text,file,free_tags
5,abc,blahblah,,"nah,wha,blah"

models.py

from django.db import models
from django.urls import reverse
from taggit.managers import TaggableManager

class KnowHow(models.Model):    

    author = models.ForeignKey('auth.User',on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = models.TextField(blank=True)
    file = models.FileField(blank=True,upload_to='explicit_knowhows')
    free_tags = TaggableManager(blank=True)

    def __str__(self):
        return self.title

admin.py

from django.contrib import admin
from import_export import resources
from import_export import fields
from import_export.admin import ImportExportModelAdmin

from .models import KnowHow
# Register your models here.

class KnowHowResource(resources.ModelResource):

    class Meta:
        model = KnowHow
        exclude = 'id'
        import_id_fields = ('title', )

@admin.register(KnowHow)
class knowHowAdmin(ImportExportModelAdmin):
    resource_class = KnowHowResource

The error says that author_id is missed.

Django adds a postfix to all the ForeignKey fields, so you should try to modify the file renaming the column:

author_id,title,text,file,free_tags
5,abc,blahblah,,"nah,wha,blah"

It fixed when I saved the CSV by encoding in UTF-8. This will not support non-alphabet letter so I recommend using .xlsx file instead. Thank you to everyone who tried to fix my problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM