从数据库加载的Django表单选项不会更新

时间:2015-09-07 15:04:30

标签: django django-forms

我收到了一份表单,用于从我的数据库中列出客户。

JDialog

接下来,我得到了一个带有“添加客户”表格的模态窗口。

问题: 当我通过模式表单将新客户插入数据库(实际上正在工作)时,在重新启动本地服务器之前,它不会出现在CustomerForm的选项中。

我需要一种方法来在添加客户后尽快更新列表。 尝试使用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]) 方法,但没有运气..

1 个答案:

答案 0 :(得分:4)

您的代码未显示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>])