2011-08-23 56 views
0

我有表單類:如何修改類的表單選擇?

class Form(forms.ModelForm): 
    id = forms.ModelChoiceField(queryset=Option.objects.all(), widget=forms.HiddenInput()) 
    category = forms.ModelChoiceField(queryset=Category.objects.all()) 

    class Meta: 
     model = Option 
     fields = ('id', 'category') 

    def choices(self, ext_data): 
     # something with extdata... 
     choices = [('1','one')] 
     category = forms.ModelChoiceField(queryset=choices) 

但這:

my_form.choices(something) 

不工作。爲什麼?

我必須在課堂上實現這一點,因爲我有一個視圖和許多不同的形式。每個表格都有特定的選擇功能。

回答

4

首先,查詢集必須是一個查詢集,而不是一個列表,因爲你使用ModelChoiceField。其次,參考category表格字段使用self.fields['category']。因此,你的函數應該是這個樣子:

def choices(self, ext_data): 
    #I'm not sure what ext_data is, but I suspect it's something to filter the Categories 
    self.fields['category'].queryset = Category.objects.filter(something=ext_data) 

    #If ext_data itself is a queryset you can use it directly: 
    self.fields['category'].queryset = ext_data 

對於澄清,一個QuerySet是你得到什麼,當你使用Model.objects.filter(xxx)或模型的任何其他過濾作用。

0

嘗試使用初始化:

class MessageAdminForm(forms.ModelForm): 
    def __init__(self, *arg, **kwargs): 
     super(MessageAdminForm, self).__init__(*args, **kwargs) 

     # set choices this way 
     self.fields['field'].choices = [(g.id, g) for g in something] 
+0

-1這適用於'ChoiceField',但不適用於'ModelChoiceField' – wim