2015-09-07 71 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

相关问题