我是Django的新手,正在构建测验应用程序。我希望能够使用管理站点上的import_export.admin方法从Django中的CSV文件导入一些问题,当我尝试导入时,包含问题列表的CSV文件的内容不会追加到现有文件中问题列表相反,它引发错误“以10为底的'int()无效文字:'独立'。”
我尝试将要上传的CSV文件的格式从逗号分隔的值更改为CSV UTF-8(逗号分隔)。我还尝试在“类别”列中使用整数,但是它给出了“回溯(最近一次呼叫最近)类别匹配查询不存在”错误。有帮助吗?
我的admin.py文件:
class QuizAdmin(admin.ModelAdmin):
form = QuizAdminForm
list_display = ('title', 'category', )
list_filter = ('category',)
search_fields = ('description', 'category', )
class CategoryAdmin(admin.ModelAdmin):
search_fields = ('category', )
class MCQuestionAdmin(ImportExportModelAdmin):
list_display = ('content', 'category', )
list_filter = ('category',)
fields = ('content', 'category',
'figure', 'quiz', 'explanation', 'answer_order')
search_fields = ('content', 'explanation')
filter_horizontal = ('quiz',)
inlines = [AnswerInline]
我的models.py文件:
class CategoryManager(models.Manager):
def new_category(self, category):
new_category = self.create(category=re.sub('\s+', '-', category).lower())
new_category.save()
return new_category
class Category(models.Model):
category = models.CharField(verbose_name=_("Category"),
max_length=250, blank=True,
unique=True, null=True)
objects = CategoryManager()
class Meta:
verbose_name = _("Category")
verbose_name_plural = _("Categories")
def __str__(self):
return self.category
class Question(models.Model):
"""
Base class for all question types.
Shared properties placed here.
"""
quiz = models.ManyToManyField(Quiz,
verbose_name=_("Quiz"),
blank=True)
category = models.ForeignKey(Category,
verbose_name=_("Category"),
blank=True,
null=True, on_delete=models.CASCADE)
figure = models.ImageField(upload_to='uploads/%Y/%m/%d',
blank=True,
null=True,
verbose_name=_("Figure"))
content = models.CharField(max_length=1000,
blank=False,
help_text=_("Enter the question text that "
"you want displayed"),
verbose_name=_('Question'))
explanation = models.TextField(max_length=2000,
blank=True,
help_text=_("Explanation to be shown "
"after the question has "
"been answered."),
verbose_name=_('Explanation'))
objects = InheritanceManager()
class Meta:
verbose_name = _("Question")
verbose_name_plural = _("Questions")
ordering = ['category']
def __str__(self):
return self.content
def create_new_question(data):
questions = Question.objects.create_new_question(quiz=data['quiz'],
category=data['category'],
content=data['content'],
explanation=data['explanation'])
questions.save()
上传文件时出现错误:
以10为底的int()无效文字:'Independence'
答案 0 :(得分:2)
在创建问题时,对于类别,应使用现有类别的ID,而不是字符串值或随机整数。
您已经创建了一些类别吗?