ModelForm 和保存的奇怪行为

发布于 2024-07-26 06:45:43 字数 538 浏览 8 评论 0原文

这个问题很奇怪,我希望有人能帮助我。 为了便于论证,我有一个 Author 模型,它与 Book 模型具有外键关系。 当我显示作者时,我希望有一个 ChoiceField 只显示与该作者相关的书籍。 因此,我重写了 AuthorForm.init() 方法,并根据根据作者 ID 筛选书籍的查询创建了一个选项列表(元组)。 该元组是图书 ID 和图书名称的组合(即 (1, 'Moby Dick'))。 然后将这些“选择”分配给 ModelForm 的选项属性。

当表单在模板中呈现时,ChoiceField 会正确显示,仅列出与该作者关联的那些书籍。

这就是事情变得奇怪的地方。

当我保存表单时,我收到一个 ValueError (无法分配“u'1'”:Author.book”必须是一个 Book 实例)。由于 FK 关系,这个错误是有意义的。但是,如果我添加一个“print”对代码进行声明,不进行其他更改,然后保存记录,它会神奇地消失,我已经尝试过多次,确保我没有无意中进行其他更改,并且每次都有效。

有谁知道这是怎么回事?

This problem is very strange and I'm hoping someone can help me. For the sake of argument, I have a Author model with ForeignKey relationship to the Book model. When I display an author, I would like to have a ChoiceField that ONLY displays the books associated with that author. As such, I override the AuthorForm.init() method and I create a List of choices (tuples) based upon a query that filters books based upon the author ID. The tuple is a composite of the book ID and the book name (i.e., (1, 'Moby Dick')). Those "choices" are then assigned to the ModelForm's choices attribute.

When the form renders in the template, the ChoiceField is properly displayed, listing only those books associated with that author.

This is where things get weird.

When I save the form, I receive a ValueError (Cannot assign "u'1'":Author.book" must be a Book instance). This error makes sense due to the FK relationship. However, if I add a "print" statement to the code, make no other changes, and then save the record, it works. The ValueError magically disappears. I've tried this a number of times, ensuring I haven't inadvertently made another change, and it works each time.

Does anyone know what's going on here?

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

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

发布评论

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

评论(1

是伱的 2024-08-02 06:45:43

不太确定你做错了什么,但最好只修改查询集:

class ClientForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        self.affiliate = kwargs.pop('affiliate')
        super(ClientForm, self).__init__(*args, **kwargs)
        self.fields["referral"].queryset = Referral.objects.filter(affiliate = self.affiliate)

    class Meta:
        model = Client

上面直接来自我的项目,它可以完美地仅显示与传递的联营公司相关的推荐对象:

form = ClientForm(affiliate=request.affiliate)

Not quite sure what you are doing wrong, but it is best to just modify the queryset:

class ClientForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        self.affiliate = kwargs.pop('affiliate')
        super(ClientForm, self).__init__(*args, **kwargs)
        self.fields["referral"].queryset = Referral.objects.filter(affiliate = self.affiliate)

    class Meta:
        model = Client

The above is straight out of one my projects and it works perfectly to only show the Referral objects related to the passed affiliate:

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