Database: Document has many Sections, Sections has many Comments
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
开发者_开发百科and my view is just:
form = CommentForm()
How do I pass CommentForm a document id?
Edit: Tried in my view:
d = Document.objects.get(id=id)
c = Comment(d)
form = CommentForm(c)
but document_id is still None in CommentForm
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)
and in the view
def my_view(request):
...
doc = Document.objects(...)
form = CommentForm(doc_id = doc.id)
EDIT
I edited the second line of the view, which I think deals with your comment? (make doc.id) a keyword arguement
精彩评论