2015-09-07 69 views
1

我收到了一個表單,用於從我的數據庫中列出客戶。從數據庫加載的Django表單選擇不會更新

class CustomerForm(forms.Form): 

customer = forms.ChoiceField(choices=[], required=True, label='Customer') 

def __init__(self, *args, **kwargs): 
    super(CustomerForm, self).__init__(*args, **kwargs) 
    self.fields['customer'] = forms.ChoiceField(choices=[(addcustomer.company_name + ';' + addcustomer.address + ';' + addcustomer.country + ';' + addcustomer.zip + ';' + addcustomer.state_province + ';' + addcustomer.city, 
                  addcustomer.company_name + ' ' + addcustomer.address + ' ' + addcustomer.country + ' ' + addcustomer.zip + ' ' + addcustomer.state_province + ' ' + addcustomer.city) for addcustomer in customers]) 

接下來,我得到了一個模式窗口,裏面有一個「添加客戶」窗體。

問題: 當我通過模式表單將新客戶插入數據庫(實際上正在工作)時,直到我重新啓動本地服務器之後,它纔會出現在CustomerForm的選項中。

我需要一種方法來在添加客戶後儘快更新列表。 試用__init__方法,但沒有運氣..

回答

3

您的代碼不顯示在哪裏定義customers。在__init__方法中移動該行,以便在表單初始化時取出,而不是在服務器啓動時取出。

class CustomerForm(forms.Form): 
    customer = forms.ChoiceField(choices=[], required=True, label='Customer') 

    def __init__(self, *args, **kwargs): 
     super(CustomerForm, self).__init__(*args, **kwargs) 
     customers = Customer.objects.all() # move this line inside __init__! 
     self.fields['customer'] = forms.ChoiceField(choices=[<snip code that uses customers>]) 
+0

太棒了,非常感謝! – s4igon

相關問題