2009-04-10 73 views
5

的選擇比方說,我有一些做作型號:如何修改ModelMultipleChoiceField

class Author(Model): 
    name = CharField() 

class Book(Model): 
    title = CharField() 
    author = ForeignKey(Author) 

而且我們說,我想使用的ModelForm的書:

class BookForm(ModelForm): 
     class Meta: 
     model = Book 

簡單爲止。但是讓我們也說我的數據庫中有很多作者,而且我不想有這麼長的多選題。所以,我想要限制BookForm的ModelMultipleChoiceField作者字段上的查詢集。我們還要說,我想要的查詢集只能在__init__之前選擇,因爲它依賴於要傳遞的參數。

這似乎是它可能做的伎倆:

class BookForm(ModelForm): 
    class Meta: 
     model = Book 

    def __init__(self, letter): 
     # returns the queryset based on the letter 
     choices = getChoices(letter) 
     self.author.queryset = choices 

當然,如果這只是工作,我就不會在這裏。這讓我一個AttributeError。 'BookForm'對象沒有屬性'作者'。所以,我也嘗試過這樣的事情,在這裏我試圖重寫的ModelForm的默認域,然後將其設:

class BookForm(ModelForm): 
    author = ModelMultipleChoiceField(queryset=Author.objects.all()) 

    class Meta: 
     model = Book 

    def __init__(self, letter): 
     choices = getChoices(letter) 
     self.author.queryset = choices 

將會產生相同的結果。

任何人都知道這是如何完成的?

回答

8

表單對象沒有自己的領域屬性,則需要在「域」屬性,這是一本字典看:

self.fields['author'].queryset = choices 

如果你想完全明白是怎麼回事,你可能對this answer感興趣 - 它是關於Models的,但Forms的工作方式相似。

7

儘管Carl對這些字段是正確的,但您也錯過了超類調用。我是這樣做的:

class BookForm(ModelForm): 
    author = ModelMultipleChoiceField(queryset=Author.objects.all()) 

    class Meta: 
     model = Book 

    def __init__(self, *args, **kwargs): 
     letter = kwargs.pop('letter') 
     super(BookForm, self).__init__(*args, **kwargs) 
     choices = getChoices(letter) 
     self.fields['author'].queryset = choices 
+0

是的,我真正的問題領域有超類調用,但我跳過了這個例子。 – Brian 2009-04-10 18:38:05