0
数据库: 文件有许多,款款有许多评论Django的,为的ModelForm修改查询集时传递信息
在每个文档页面上,有一个评论表单,让你挑选部分(使用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()
我如何通过CommentForm文档ID?
编辑:我认为尝试:
d = Document.objects.get(id=id)
c = Comment(d)
form = CommentForm(c)
但DOCUMENT_ID仍然没有在CommentForm
后者将用于编辑现有的对象,除非我走了?现在踢自己,如此明显!谢谢 – bcoughlan 2011-06-01 19:06:45
只是我的额外2美分...我认为这是更好的更改这样的查询集: 'self.fields ['section']。queryset = self.fields ['section']。queryset.filter( document__id = doc_id)' – 2011-06-01 19:32:46
@beres谢谢,这很好。 @pastylegs - 这个方法实际上遇到了一个问题,因为当Django在使用.save()时调用CommentForm时,* args将会丢失它的第一个参数。我知道这里有一些黑客攻击,但是这肯定是Django中一个非常常见的任务,它不应该被黑客利用... – bcoughlan 2011-06-01 21:07:22