0

I have a dynamically created form build with Django. When this form is submitted i can see all the data in request.post, that being said when i access form.cleaned_data one of the inputs is not there. This is causing a KeyError when i try to access it.

There are no errors caused by the form and the form is appearing valid. If anyone has any other avenues i could look, i would be very appreciative.

Here is the error:

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

Here is the View although i don't feel it will help:

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))])

Here is the form:

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
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
blobbymatt
  • 317
  • 1
  • 2
  • 17

4 Answers4

0

You should always return collection of cleaned data. Probably you've forget to return cleaned_data in your clean method so self.cleaned_data will not be populated.

kuter
  • 204
  • 2
  • 5
  • clean_data is populated with many other inputs that have been removed from the code for easier viewing. This form has 32 inputs and this DropdownList_6 is the only one not in clean_data – blobbymatt Apr 09 '19 at 12:56
0

where do you increment "a"? maybe your while loop is running forever and you get a key error when you run out of questions. Are you sure in your example there was an actual question[6]?

Rosey
  • 739
  • 1
  • 12
  • 27
0

Ended up, as i was re-using code i forgot the change the name of the form i was calling. I should have been calling the StrategicBriefForm in the view instead of the OutlineBusinessCaseForm.

Thanks everyone who tried to help.

blobbymatt
  • 317
  • 1
  • 2
  • 17
0

when i use this print(self.request.user) it should print the current user but cannot modified user with table in admin panel .

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

its work sucessfully. try this command