从数据库加载的 Django 表单选择不会更新
Django form choices loaded from database are not updated
我得到了一个表格,用于从我的数据库中列出客户。
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])
接下来我得到了一个模态 window,里面有一个 "add customer" 表单。
问题:
当我通过模态表单将新客户插入数据库(实际上正在运行)时,在我重新启动本地服务器之前,它不会出现在 CustomerForm 的选项中。
我需要一种在添加客户后尽快更新列表的方法。
尝试使用 __init__
方法但没有成功..
您的代码未显示 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>])
我得到了一个表格,用于从我的数据库中列出客户。
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])
接下来我得到了一个模态 window,里面有一个 "add customer" 表单。
问题: 当我通过模态表单将新客户插入数据库(实际上正在运行)时,在我重新启动本地服务器之前,它不会出现在 CustomerForm 的选项中。
我需要一种在添加客户后尽快更新列表的方法。
尝试使用 __init__
方法但没有成功..
您的代码未显示 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>])