如何在 django-import/export 上导入 auth.User
How to import auth.User on django-import/export
我无法将 CSV 文件导入到 Django 上的模型中。
我创建了一个列 'author' 并将我登录到管理站点的超级用户的 ID 放入。
但是导入CSV文件的时候出现了这样的错误
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 文件
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
错误说 author_id
被遗漏了。
Django adds a postfix 到所有 ForeignKey
字段,所以你应该尝试修改文件重命名列:
author_id,title,text,file,free_tags
5,abc,blahblah,,"nah,wha,blah"
当我通过 UTF-8 编码保存 CSV 时,它已修复。这将不支持非字母字母,因此我建议改用 .xlsx 文件。
感谢所有试图解决我的问题的人。
我无法将 CSV 文件导入到 Django 上的模型中。 我创建了一个列 'author' 并将我登录到管理站点的超级用户的 ID 放入。 但是导入CSV文件的时候出现了这样的错误
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 文件
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
错误说 author_id
被遗漏了。
Django adds a postfix 到所有 ForeignKey
字段,所以你应该尝试修改文件重命名列:
author_id,title,text,file,free_tags
5,abc,blahblah,,"nah,wha,blah"
当我通过 UTF-8 编码保存 CSV 时,它已修复。这将不支持非字母字母,因此我建议改用 .xlsx 文件。 感谢所有试图解决我的问题的人。