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

s4i*_*gon 2 django django-forms

我从数据库中获得了用于列出客户的表格。

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])
Run Code Online (Sandbox Code Playgroud)

接下来,我得到一个模态窗口,里面有一个“添加客户”表单。

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

我需要一种在添加客户后尽快更新列表的方法。尝试过这种__init__方法,但没有运气。

Ala*_*air 5

您的代码未显示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>])
Run Code Online (Sandbox Code Playgroud)