【发布时间】:2019-01-30 01:07:55
【问题描述】:
我正在使用formset_factory 在我的页面上管理几个相同的表单。在每种形式中,都有一对链式下拉菜单。 DropdownA 有一个 onchange 事件,它请求 dropdownB (AJAX) 的选项。这一切都很好,但是当我通过 POST 请求提交表单时,它们都未通过forms.is_valid() 检查。打印提交的表单集的错误揭示了原因:
[{'DropdownB ': ['Select a valid choice. Like is not one of the available choices.']}, {'DropdownB ': ['Select a valid choice. < is not one of the available choices.']}]
有两个错误,每个表单一个。他们都抱怨为 DropdownB 发送的选项不是可用的选项之一(恭敬地“喜欢”和“
现在,因为我只想根据 DropdownA 选择的内容用某些选项填充 DropdownB,所以我特意用 0 个选项定义了 DropdownB(一个选择字段)。
DropdownB = ()
DropdownB = forms.ChoiceField(choices=op_choices, required=False)
如何根据 DropdownA 的值向服务器指定哪些有效选项?
我试图在上面的摘要中简化这个问题,但是如果你想要表单的完整代码,这里你去:
class UnifiedSingleSearchBar(forms.Form):
# Dict to categorize field types
type_dict = {
'DateField': 'Numeric',
'DateTimeField': 'Numeric',
'AutoField': 'Numeric',
'CharField': 'String',
'BooleanField': 'Bool',
}
operation_dict = {'Numeric':
(
('>', '>'),
('>=', '>='),
('<', '<'),
('<=', '<='),
('=', '='),
('>-<', 'Between'),
('0', 'IS null'),
('1', 'IS NOT null'),
),
'String':
(
('Like', 'Like'),
('Is', 'Is')
),
'Bool':
(
('True', 'True'),
('False', 'False')
)
}
searchabel_field_choices = ()
# To create the "field" dropdown, we loop through every field in the model and note its type.
for field in Mymodel._meta.fields:
tuple = (
(field.name, field.name), # signifies a nested tuple
)
searchabel_field_choices = searchabel_field_choices + tuple
searchabel_field_choices = searchabel_field_choices + (('', '--------'),)
shared_attrs = {
'autocomplete': 'off',
'class': 'form-control datetimepicker-input',
}
searchable_field = forms.ChoiceField(choices=searchabel_field_choices, required=False)
op_choices = () # Should always start with an empty operations list since field has not yet been chosen
operation = forms.ChoiceField(choices=op_choices, required=False)
# 2 is usually only ever used if a range is being specified
# Numeric
date1 = forms.DateField(required=False, widget=DatePicker(attrs=shared_attrs))
date2 = forms.DateField(required=False, widget=DatePicker(attrs=shared_attrs))
datetime1 = forms.DateTimeField(required=False, widget=DateTimePicker(attrs=shared_attrs))
datetime2 = forms.DateTimeField(required=False, widget=DateTimePicker(attrs=shared_attrs))
integer = forms.IntegerField(required=False)
# Bool
bool = forms.BooleanField(required=False)
# String
string = forms.CharField(required=False)
【问题讨论】:
-
您是否知道要真正实现这一点,您需要实现一些 javascript?通常,您通过更改 dropdownA 后启动的脚本来更改 dropdownB 的内容。如果没有 javascripot,您将需要服务器交互。然后您需要更改表单 init 方法中的下拉菜单。
-
什么意思?我正在用 Javascript 更改 dropdownB。我认为提到我使用 AJAX 很明显,但如果这意味着与我所做的不同,是的,我使用的是 Javascript。我的问题只是服务器端。我对客户体验没有任何问题。
-
我忽略了第一行。您可能需要提供更多代码。你能出示你的表格吗?
-
我进行了编辑以将其包含在问题中。
-
你在改变 ajax 调用中的 op_choices 吗?
标签: django django-forms