Django - 发布不在form.cleaned_data中的数据导致密钥错误

问题描述 投票:0回答:3

我有一个动态创建的表单构建与Django。当提交此表单时,我可以看到request.post中的所有数据,当我访问form.cleaned_data时,其中一个输入不存在。当我尝试访问它时,这会导致KeyError。

表单不会导致错误,表单显示有效。如果任何人有任何其他途径我可以看,我会非常感激。

这是错误:

Internal Server Error: /gluiq/StrategicBrief/
Traceback (most recent call last):
  File "/Users/matthew/python3venv/gluiq/lib/python3.7/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/Users/matthew/python3venv/gluiq/lib/python3.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/matthew/python3venv/gluiq/lib/python3.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/matthew/python3venv/gluiq/lib/python3.7/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/matthew/python3venv/gluiq/lib/python3.7/site-packages/braces/views/_access.py", line 102, in dispatch
    request, *args, **kwargs)
  File "/Users/matthew/python3venv/gluiq/lib/python3.7/site-packages/django/views/generic/base.py", line 88, in dispatch
    return handler(request, *args, **kwargs)
  File "/Users/matthew/PycharmProjects/GluIQ/DreamIt/views.py", line 494, in post
    ThisAwnser = str(form.cleaned_data[str('DropdownList_' + str(a))])
KeyError: 'DropdownList_6'
[09/Apr/2019 12:25:51] "POST /gluiq/StrategicBrief/ HTTP/1.1" 500 97452

这是视图,虽然我觉得它不会有所帮助:

def post(self, request):
    if request.method == 'POST':
        files = Files.objects.get(FileName="Strategic Brief")
        self.request.session['activeFile'] = files.id
        form = OutlineBusinessCaseForm(request.POST, request.FILES, Questions=files.questions.all())
        activeproject = request.session['activeProject']

        print(form.errors)
        if form.is_valid():

            current_user = self.request.user
            projects = userProject.objects.filter(id=activeproject, UserID=current_user)
            file = Files.objects.get(FileName="Strategic Brief")
            questions = file.questions.all()
            awnseredQuestion = QuestionAwner(UserID=self.request.user, ProjectID=projects[0].ProjectID, FileID=file)

            a = 0
            while a < len(questions):
                awnseredQuestion = QuestionAwner(UserID=self.request.user, ProjectID=projects[0].ProjectID,
                                                 FileID=file)
                awnser = '{"Title": "' + questions[a].Question['Title'] + '",' + '"AwnserTitle": "' + \
                         questions[a].Question['AwnserTitle'] + '",'



                if questions[a].Question['DropdownList'] == True:
                    ThisQuestion = questions[a].Question['DropdownList_Question']
                    ThisAwnser = str(form.cleaned_data[str('DropdownList_' + str(a))])

这是表格:

class StrategicBriefForm(forms.Form):

    def __init__(self, *args, **kwargs):

        questions = kwargs.pop("Questions", None)
        super(StrategicBriefForm, self).__init__(*args, **kwargs)
        if questions:
            i = 0
            while i < len(questions):
                question = questions[i].Question

                if question['DropdownList'] == True:
                    self.fields['DropdownList_%s' % i] = forms.CharField(label=question['DropdownList_Question']['context'],
                                                                  required=False)

                i = i + 1
python django typeerror django-1.11
3个回答
0
投票

您应该始终返回已清理数据的集合。可能您忘记在clean方法中返回cleaning_data,因此不会填充self.cleaned_data。


0
投票

你在哪里递增“a”?也许你的while循环永远在运行,当你用完问题时你会得到一个关键错误。你确定在你的例子中有一个实际问题[6]吗?


0
投票

结束了,因为我重新使用代码我忘了更改我正在调用的表单的名称。我应该在视图中调用StrategicBriefForm而不是OutlineBusinessCaseForm。

谢谢所有试图提供帮助的人。

© www.soinside.com 2019 - 2024. All rights reserved.