Django - Post 数据不在 form.cleaned_data 中导致键错误

Django - Post data not in form.cleaned_data leading to key error

我有一个用 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

您应该始终return 收集清理过的数据。可能您忘记了 return cleaned_data 在您的清洁方法中,因此 self.cleaned_data 将不会被填充。

你在哪里递增 "a"?也许你的 while 循环永远 运行ning 并且当你 运行 出问题时你会得到一个关键错误。你确定在你的例子中有一个实际的问题[6]?

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

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

当我使用此 print(self.request.user) 时,它应该打印当前用户,但不能在管理面板中使用 table 修改用户。

shrt = form.save(commit=False)
shrt.user = request.user
        shrt.save()
        form.save()

它的工作成功了。试试这个命令