我正在开发一个使用django的应用程序,当用户与它交互时,UI需要更新。例如,我有一个下拉字段,用户选择一种饮料并提交它,然后根据下拉字段显示有饮料的地方,每个地方的价格和数量需要显示。然后,用户将进一步提交表单以进行第二次处理。
根据我的理解,django中的form是预定义的,我想不出一种方法来实现这一点。
我能想到的是定义一个正则表单类
class dform(forms.Form):
SOURCES_CHOICES = (
(A, 'A'),
(E, 'E'),
)
drink = forms.ChoiceField(choices = SOURCES_CHOICES)
location = forms.ChoiceField(choices = **GET THIS FROM DATABASE**)
quantity = forms.ChoiceField(choices = **GET THIS FROM DATABASE**)
.
.
.
我的观点是,
def getdrink():
if request.method == 'POST':
#code for handling form
drink = dform.cleaned_data['drink']
#code to get values from database
我不知道如何生成或填充或附加我从数据库得到的值到我的表单中的选择字段。我确实尝试过查找SO,但这里没有一个解决方案可以正确解释如何做到这一点。此外,由于某些要求,我没有使用模型。因此,我的数据库与模型完全无关。
我完全不知道该怎么办
class MyForm(forms.Form):
my_choice_field = forms.ChoiceField(choices=MY_CHOICES)
所以如果你想让值是动态的(或依赖于一些逻辑),你可以简单地修改你的代码像这样:
def get_my_choices():
# you place some logic here
return choices_list
class MyForm(forms.Form):
my_choice_field = forms.ChoiceField(choices=get_my_choices())
或
User_list = [ #place logic here]
class MyForm(forms.Form):
my_choice_field = forms.ChoiceField(choices=get_my_choices())
但是一旦数据库值被更新,新的数据值将只在服务器重新启动时填充。因此,在forms中编写如下函数:
class MyForm(forms.Form):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['my_choice_field'] = forms.ChoiceField( choices=get_my_choices() )
或者代替get_my_choices,你也可以添加USER_LIST
如果您有location
和quantity
的模型,一个ModelChoiceField应该工作:
class dform(forms.Form):
location = forms.ModelChoiceField(queryset = Location.objects.all())
否则,需要直接查询数据库,例如:
class dform(forms.Form):
location = forms.ChoiceField(choices = get_location_choices())
# elsewhere
from django.db import connection
def get_location_choices():
cursor = connection.cursor()
cursor.execute("select location_id, name from location_table")
return cursor.fetchall()
这里使用的SQL查询取决于您的数据库引擎和表模式。
我认为,根据我对你的问题的理解,最好的解决方案是在你的表单中包含JSON对象,并使用jQuery加载这些对象,而不是一遍又一遍地提交表单。在表单中,您应该添加如下内容:
class MyForm(forms.Form):
CHOICE_DICT = {
'choice_1': [
'option_1',
'option_2',
],
etc...
那么你应该包括表单。