gpt4 book ai didi

python - 提交 django 表单集时出现 MultiValueDictKeyError

转载 作者:太空宇宙 更新时间:2023-11-03 16:29:21 24 4
gpt4 key购买 nike

我正在开发一个 Django 应用程序,我试图一次性提交一个表单和一个表单集。

让表单集渲染工作完美,但使用 POST 提交它会产生错误...一旦我注释掉从 POST 数据生成表单集,一切正常,并且表单提交没有错误

问题是,我得到的错误不是很具有描述性:

MultiValueDictKeyError at /questions/question/add
'0'

这些是我的查看方法:

def get(self, request, question_id=-1):
initial_data = {
'categories': 1,
'subcategories': 2,
'questionEditor': "Test initial",
'isOpenQuestion': True,
'isMultiChoice': False,
}

category = request.session['category'] if 'category' in request.session else 0
initial_data['categories'] = category

formset_initial_data = list()
if question_id > 0:
question = Question.objects.get(id=question_id)
initial_data = {
'categories': question.subcategories.category.id,
'subcategories': question.subcategories.id,
'questionEditor': question.description,
'isOpenQuestion': question.isOpenQuestion,
'isMultiChoice': question.isMultiChoice,
}

for index, answer in enumerate(question.answer_set.all()):
print answer.description
formset_initial_data.append({
'formulaAnswerEditor': answer.description,
'answerInputBox': answer.isCorrect,
})

question_edit_formset = formset_factory(forms.QuestionEditAnswerForm, extra=(3 if len(formset_initial_data) == 0 else 0))
formset = question_edit_formset(initial=formset_initial_data)

form = forms.QuestionEditForm(data=initial_data)
data = {
'form': form,
'formset': formset,
}
return render(request, "questionEdit.html", dictionary=data)


def post(self, request, question_id=-1):
print request.POST
form = forms.QuestionEditForm(data=request.POST)
question_answers_formset = formset_factory(forms.QuestionEditAnswerForm, extra=0)
formset = question_answers_formset(initial=request.POST)

print form, formset

表单类

class QuestionEditAnswerForm(forms.Form):
id = forms.IntegerField(widget=forms.HiddenInput())
answerInputBox = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={
'class': 'answer-input-type',
'type': 'radio',
}))

formulaAnswerEditor = forms.CharField(widget=forms.Textarea(attrs={
'class': "answer-text-area-style answer-cke-remove-bottom-toolbar cke-placeholder"}))

模板:

{{ formset.management_form }}

{% for single_answer in formset %}

{{ single_answer.id }}
<div class="margin-answer">
<div class="input-group">
<span class="input-group-addon">
{{ single_answer.answerInputBox }}
</span>
{{ single_answer.formulaAnswerEditor }}
</div>
</div>
{% endfor %}

使用 JS 将新表单添加到表单集中,但即使我不添加任何新表单,错误仍然存​​在......

我尝试过遵循类似问题的答案,但到目前为止没有运气

如果有人知道如何解决这个问题,我将不胜感激:)

编辑:完整的回溯(我对 Django 和 Python 比较陌生,所以这对我来说并没有说太多:))

Request Method: POST
Request URL: http://localhost:8000/questions/question/add

Django Version: 1.9.6
Python Version: 2.7.11
Installed Applications:
['suit',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'MainPage',
'News',
'Registration',
'StaticSites',
'UserDetails',
'Questions',
'Competitions']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "/path/to/env/env/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)

File "/path/to/env/env/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/path/to/env/env/lib/python2.7/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)

File "/path/to/env/env/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)

File "/path/to/env/ekonkurs/Questions/views.py" in post
221. print form, formset

File "/path/to/env/env/lib/python2.7/site-packages/django/utils/six.py" in <lambda>
842. klass.__str__ = lambda self: self.__unicode__().encode('utf-8')

File "/path/to/env/env/lib/python2.7/site-packages/django/utils/html.py" in <lambda>
381. klass.__unicode__ = lambda self: mark_safe(klass_unicode(self))

File "/path/to/env/env/lib/python2.7/site-packages/django/forms/formsets.py" in __str__
70. return self.as_table()

File "/path/to/env/env/lib/python2.7/site-packages/django/forms/formsets.py" in as_table
413. forms = ' '.join(form.as_table() for form in self)

File "/path/to/env/env/lib/python2.7/site-packages/django/forms/formsets.py" in __iter__
74. return iter(self.forms)

File "/path/to/env/env/lib/python2.7/site-packages/django/utils/functional.py" in __get__
33. res = instance.__dict__[self.name] = self.func(instance)

File "/path/to/env/env/lib/python2.7/site-packages/django/forms/formsets.py" in forms
144. for i in range(self.total_form_count())]

File "/path/to/env/env/lib/python2.7/site-packages/django/forms/formsets.py" in _construct_form
170. defaults['initial'] = self.initial[i]

File "/path/to/env/env/lib/python2.7/site-packages/django/utils/datastructures.py" in __getitem__
85. raise MultiValueDictKeyError(repr(key))

Exception Type: MultiValueDictKeyError at /questions/question/add
Exception Value: '0'

最佳答案

问题出在您的 post 方法中:您将数据作为 initial 参数传递到表单集,而不是作为 data 作为你用表格来做。

(请注意,您似乎在 get 方法中犯了相反的错误;您将初始数据作为 data 而不是 传递到表单初始。)

关于python - 提交 django 表单集时出现 MultiValueDictKeyError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37743784/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com