猿问

Django:无法验证 MultipleChoiceField

问题


我的MultipleChoiceField. 我可以从CheckboxSelectMultiplemy 中的一个小部件中看到我的条目列表request.POST,但是当显式调用该参数时,它只返回我的第一个条目。该表单也没有验证我收到的错误:


 File "C:\Users\lhepburn\Anaconda3\lib\site-packages\django\forms\forms.py", line 185, in is_valid

    return self.is_bound and not self.errors

  File "C:\Users\lhepburn\Anaconda3\lib\site-packages\django\forms\forms.py", line 180, in errors

    self.full_clean()

  File "C:\Users\lhepburn\Anaconda3\lib\site-packages\django\forms\forms.py", line 383, in full_clean

    self._post_clean()

  File "C:\Users\lhepburn\Anaconda3\lib\site-packages\django\forms\models.py", line 398, in _post_clean

    self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)

  File "C:\Users\lhepburn\Anaconda3\lib\site-packages\django\forms\models.py", line 60, in construct_instance

    f.save_form_data(instance, cleaned_data[f.name])

  File "C:\Users\lhepburn\Anaconda3\lib\site-packages\django\db\models\fields\__init__.py", line 853, in save_form_data

    setattr(instance, self.name, data)

  File "C:\Users\lhepburn\Anaconda3\lib\site-packages\django\db\models\fields\related_descriptors.py", line 211, in __set__

    self.field.remote_field.model._meta.object_name,

ValueError: Cannot assign "['1', '2', '3']": "CanisterModel.test_cell" must be a "CellModel" instance.


所以如果我打印request.POST我得到:


<QueryDict: {'csrfmiddlewaretoken': ['9KwmPg1GzSXL98kjQbUHsvJGCIX3zNiBgqPbMPVtZtxYXKGnlZjreN9tDtDSdxiC'], 'test_cell': ['1', '2', '3'], 'canister_type': ['Total Hydrocarbons'], 'canister_change_date': ['07/07/2020'], 'time_field': ['12:30'], 'actual_conc': ['123']}>

如果我打印request.POST['test_cell']我得到:


'3'

如果我打印request.POST.getlist('test_cell')我得到:


['1', '2', '3']

更奇怪的是,如果我调试到调用的断点并在调试终端中if update_canister_form.is_valid():运行,它会返回True并且脚本会继续。update_canister_form.is_valid()


我想要的是


我想验证表单而不必复制和操作 request.POST 并将其简单地传递到表单中并进行验证。


哆啦的时光机
浏览 85回答 1
1回答

有只小跳蛙

问题源于包含test_cell在表单元字段内部。class Meta:&nbsp; &nbsp; &nbsp; &nbsp; model= CanisterModel&nbsp; &nbsp; &nbsp; &nbsp; fields = ('test_cell','canister_type','canister_change_date','actual_conc',)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;#removed&nbsp; --^这将其从该模型字段的默认验证中删除。虽然我不明白这仍然无法验证。如果有人知道请告诉我。
随时随地看视频慕课网APP

相关分类

Python
我要回答