Django 表单不验证:“选择一个有效的选择。 20 不是可用的选择之一”
我有一个由 2 个 ChoiceField 和一个 CharField 组成的表单。当选择第一个 ChoiceField 的项目时,通过 ajax 填充第二个 ChoiceField。
填充它的模板如下:
{% for a in assets %}
<option value="{{ a.asset_id }}">{{ a.asset_name }}_{{ a.asset_description }}</option>
{% endfor %}
当我尝试提交表单时,出现以下错误:
Select a valid choice. 20 is not one of the available choices.
指向第二个 ChoiceField,20 对应于所选项目的 {{a.asset_id}}。
我在其他论坛上看到了这个错误,但它几乎总是由于 multipleChoiceField 而引起的,这不是我关心的。
我做错了什么?
I have a form composed of 2 ChoiceField and a CharField. The second ChoiceField is populated via ajax when an item of the first one is selected.
The template populating it is the following :
{% for a in assets %}
<option value="{{ a.asset_id }}">{{ a.asset_name }}_{{ a.asset_description }}</option>
{% endfor %}
When I try to submit the form I get the following error :
Select a valid choice. 20 is not one of the available choices.
Pointing to the second ChoiceField, 20 corresponds to the {{a.asset_id}} of the item selected.
I saw this error on other forums but it's almost always due to multipleChoiceField which is not my concern.
What am I doing wrong ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ChoiceField 需要设置
choices
。这些不仅决定了下拉列表中显示的内容,而且对您来说重要的是,它还决定了提交表单时应接受哪些值。让我解释一下你的情况是怎么回事。您的选择最初设置为:
这意味着唯一会被接受的是空白选择(元组中的第一个条目
''
是字段的实际值,并且choisir...
是文本值)。因此,当您通过 Javascript 添加
元素时,它们的值不会出现在
CHOICES
中,因此当您提交该表单时,它们会被 Django 拒绝。 10 不在CHOICES
中。表单提交到的视图应该查看提交给它的选项的值,然后相应地更改传递到 ChoiceField 的
CHOICES
值。A ChoiceField needs to have
choices
set. These don't just determine what is shown in the dropdown, but importantly for you, it also determines what values should be accepted when the form is submitted.Let me explain what's going on in your situation. You have your choices initially set as:
This means that the only thing will be accepted is a blank choice (the first entry in the tuple,
''
, is the actual value of the field, andchoisir...
is the text value).So when you add
<option>
elements via Javascript, their values won't be inCHOICES
, and so they're getting rejected by Django when you submit that form. 10 isn't inCHOICES
.The view that your form submits to should look at the value of the option submitted to it, and then change the value of
CHOICES
passed to the ChoiceField accordingly.