Django,修改ModelForm的queryset时传递信息

1 投票
1 回答
1497 浏览
提问于 2025-04-16 18:47

数据库:一个文档可以有很多部分,每个部分又可以有很多评论。

在每个文档页面上,有一个评论表单,可以让你选择部分(使用一个叫ModelChoiceField的东西)。问题是,这个ModelChoiceField会显示所有文档的所有部分。

所以为了限制显示的部分,我这样做:

class CommentForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(CommentForm, self).__init__(*args, **kwargs)
        if self.instance:
            logger.debug(self.instance.document_id) # Prints "None"
            self.fields['section'].queryset = Section.objects.filter(document=self.instance.document)
            # ^^^ Throws DoesNotExist as self.instance.document is None

而我的视图代码就是:

form = CommentForm()

我该如何把文档的ID传给CommentForm呢?

编辑:我在我的视图中尝试了:

d = Document.objects.get(id=id)
c = Comment(d)
form = CommentForm(c)

但是在CommentForm中,document_id仍然是None。

1 个回答

5

你可以在初始化表单的时候传入文档的ID:

class CommentForm(ModelForm):
    def __init__(self, doc_id=None, *args, **kwargs):
        if doc_id:
            self.fields['section'].queryset = Section.objects.filter(document__id=doc_id)

然后在视图中使用

def my_view(request):
    ...
    doc = Document.objects(...)
    form = CommentForm(doc_id = doc.id)

编辑

我修改了视图的第二行,我觉得这和你的评论有关?(把 doc.id)作为一个关键字参数

撰写回答