2011-06-01 40 views
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

回答

3

您初始化時可以將文檔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) 

編輯

我編輯的視圖的第二行,我認爲涉及您的評論? (make doc.id)一個關鍵字的爭論

+0

後者將用於編輯現有的對象,除非我走了?現在踢自己,如此明顯!謝謝 – bcoughlan 2011-06-01 19:06:45

+2

只是我的額外2美分...我認爲這是更好的更改這樣的查詢集: 'self.fields ['section']。queryset = self.fields ['section']。queryset.filter( document__id = doc_id)' – 2011-06-01 19:32:46

+0

@beres謝謝,這很好。 @pastylegs - 這個方法實際上遇到了一個問題,因爲當Django在使用.save()時調用CommentForm時,* args將會丟失它的第一個參數。我知道這裏有一些黑客攻擊,但是這肯定是Django中一個非常常見的任務,它不應該被黑客利用... – bcoughlan 2011-06-01 21:07:22