Django在修改ModelForm的查询集时传递信息 [英] Django, passing information when modifying queryset for ModelForm
问题描述
数据库:
文档有许多部分,部分有许多评论
Database: Document has many Sections, Sections has many Comments
在每个文档页面上都有一个注释表单,可以让您选择该部分使用ModelChoiceField)。问题是ModelChoiceField将包含所有文档的所有部分。
On each document page, there is a comment form that lets you pick the section (using a ModelChoiceField). The problem is that the ModelChoiceField will contain ALL sections for all documents.
所以要限制他们,我这样做:
So to limit them I do this:
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()
如何传递CommentForm文档ID?
How do I pass CommentForm a document id?
编辑:在我的看法中尝试:
d = Document.objects.get(id=id)
c = Comment(d)
form = CommentForm(c)
但是document_id仍然没有评论表单
but document_id is still None in CommentForm
推荐答案
您可以在初始化表单时传递文档ID:
You can pass the document id when initialising the form:
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)
编辑
我编辑的第二行视图,我认为处理您的评论? (make doc.id)关键字arguement
I edited the second line of the view, which I think deals with your comment? (make doc.id) a keyword arguement
这篇关于Django在修改ModelForm的查询集时传递信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!