添加其他对象并收到错误 MultiValueDictKeyError (Django admin)

发布于 2024-12-06 15:11:49 字数 965 浏览 0 评论 0原文

我的关系如下:

class Question(models.Model):
   qid = models.PositiveIntegerField(primary_key=True)
   content = models.CharField(max_length=128)

class Answer(models.Model):
   answerid = models.PositiveIntegerField(primary_key=True)
   content = models.CharField(max_length=128)
   question = models.ForeignKey(Question)


class AnswerInline(admin.StackedInline):
   model = Answer
   readonly_fields = ('answerid',)
   extra = 0

class QuestionAdmin(admin.ModelAdmin):    
    inlines = [AnswerInline]
    exclude = ('id')
    list_display = ('content',)

admin.site.register(Question,QuestionAdmin)

假设我有一个问题A,并且我还没有这个问题的答案。 所以,当我添加 A 答案时,就可以了。但是,我尝试添加其他答案,系统输出错误 MultiValueDictKeyError:

“在 QueryDict 中找不到键“oam_answer_set-0-answerid”:...

因为 'qid' 和 'answerid' 都不是自动字段。因此,当我保存对象时,django admin 无法将新行插入数据库(缺少主键)。

,我如何自定义 AutoField?

但是,我希望主键的字段类型是 PositiveIntegerField。因此

I have a relationship follow as:

class Question(models.Model):
   qid = models.PositiveIntegerField(primary_key=True)
   content = models.CharField(max_length=128)

class Answer(models.Model):
   answerid = models.PositiveIntegerField(primary_key=True)
   content = models.CharField(max_length=128)
   question = models.ForeignKey(Question)


class AnswerInline(admin.StackedInline):
   model = Answer
   readonly_fields = ('answerid',)
   extra = 0

class QuestionAdmin(admin.ModelAdmin):    
    inlines = [AnswerInline]
    exclude = ('id')
    list_display = ('content',)

admin.site.register(Question,QuestionAdmin)

Suppose I have a question namely A and I haven't any answer for this question yet.
So, when I add an answer of A. It's ok. However, I try to add an other answer, system output an error MultiValueDictKeyError:

"Key 'oam_answer_set-0-answerid' not found in QueryDict:...

Because both of 'qid' and 'answerid' are not an AutoField. So, when I save an object, django admin can not insert a new row into database (missing primary key).

The AutoField is declared an IntegerField. However, I would like the field type of primary key is PositiveIntegerField. For that reason, how can I customize an AutoField?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

〃温暖了心ぐ 2024-12-13 15:11:49

admin ie 中注册 Answer 模型

...
admin.site.register(Answer)

尝试在 admin.py 底部的 。您正在使用从 ModelAdmin 继承的内联字段(特别是 readonly_fields),但您可能尚未注册该模型。

Try registering the Answer model with the admin i.e.

...
admin.site.register(Answer)

at the bottom of the admin.py. You are using fields on the inline (specifically readonly_fields) that are inherited from ModelAdmin, but you might not have registered that model.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文