我有一个MultipleChoiceField的奇怪问题,它不返回 POST QueryDict中的项目
这是表格
class TranslationLanguagesForm(forms.Form):
languages = forms.MultipleChoiceField(
widget=forms.SelectMultiple(attrs={"novalidate": "",}),
choices=languages,
required=False,
)
视图类似于(缩短):
class AjaxSpotlerCreateView(View):
def post(self,request):
# ...
# some code before
#
translation_form = TranslationLanguagesForm(
self.request.POST, prefix="translation"
)
if translation_form.is_valid():
translation_languages = translation_form.cleaned_data.get(
"languages"
)
#
# some code after
#
我不会编写整个模板,但表单创建的 html 符合我的预期:
<select name="translation-languages" novalidate="" class="form-control " id="id_translation-languages" multiple="">
<option value="fr">french</option>
<option value="en">english</option> <option value="es">spanish</option> </select>
通过 ajax 请求发送数据的 jquery 如下所示:
function ajaxPOST() {
var dismiss = false;
$.ajax({
method: "POST",
url: ajaxURL,
data: getFormData(),
beforeSend: function () {},
success: function (data) {
$target.find(".modal-content").html(data);
if (data.length == 0) dismiss = true;
},
complete: function () {
if (dismiss) hideUploadModal();
else showUploadModal();
}, //complete
}); //ajax
}
function getFormData() {
const result = {};
const $form = $target.find("form#video-loader-form");
const $inputs = $form.find("input, select, textarea");
$inputs.each((_, element) => {
const $element = $(element);
const type = $element.attr("type");
const name = $element.attr("name");
if (name && type == "checkbox" && $element.prop("checked"))
result[name] = $element.prop("checked");
else if (name && type != "checkbox") result[name] = $element.val();
});
return result;
}
问题是表单永远不会被 request.POST 的数据“填充”,而 translation_languages 总是收到一个空列表。
...但self.request.POST.getlist("translation-languages[]")
返回正确的值
它只发生在MultipleChoiceField而ChoiceField返回正确的值
这是 POST 数据(您看到的数据多于问题表单所需的数据,因为视图中有 4 个表单和 1 个表单集):
<QueryDict: {'csrfmiddlewaretoken': ['bQQzHTR4JDFZFnmO1ExlPZhqURHswXTmXA9RGC2c05pBM63ns2gnVwUnbnwGzor1'], '转录语言': ['en-us'], '翻译语言[]': ['fr', 'es'], 'spotlers-TOTAL_FORMS ':['1'],'spotlers-INITIAL_FORMS':['1'],'spotlers-MIN_NUM_FORMS':['0'],'spotlers-MAX_NUM_FORMS':['1000'],'spotlers-0-url ': ['https://test-dev-s.storage.googleapis.com/uploads/FR/5e24512/2021/1/9fccac26/9fc37a26-2545-434f-8bd2-0afc3df839aa_full.mp4?X-Goog-Algorithm= GOOG4-RSA-SHA256&X-Goog-Credential=storage%40funky-tower-264412.iam.gserviceaccount.com%2F20210108%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20210108T125533Z&X-Goog-Expires=3600&X-Goog-SignedHeadersx-goog-signature=8e737cbc384fab5e11002cbc5e6308'], 'spotlers-0-id': ['9fc37a26-1893-434f-8bd2-0afc3df839ef'], 'spotlers-0-name': ['ultraclimb'], 'spotlers-0 -duration':['00:02:43'],'spotlers-0-is_postedited':['true'],'keywords-keywords':[''],'glossary-glossary':['']} >
ajax POST 返回的字典似乎也为多选创建了一个奇怪的名称。该字段的名称以数组符号为后缀:[] ...所以我得到了'translation-languages[]': ['fr', 'es']
而不是'translation-languages': ['fr', 'es']