keyerror in formset form fieldHow do you disable browser Autocomplete on web form field / input tag?JavaScript post request like a form submitDynamically adding a form to a Django formset with AjaxHow to prevent buttons from submitting formsConvert form data to JavaScript object with jQueryHTML-encoding lost when attribute read from input fieldjQuery AJAX submit formWhat does enctype='multipart/form-data' mean?Cannot display HTML stringDjango form. How hidden colon from initial_text?

On which topic did Indiana Jones write his doctoral thesis?

Understanding trademark infringements in a world where many dictionary words are trademarks?

How can I support myself financially as a 17 year old with a loan?

I have a unique character that I'm having a problem writing. He's a virus!

Why do people keep telling me that I am a bad photographer?

How did Kirk identify Gorgan in "And the Children Shall Lead"?

Expressing 'our' for objects belonging to our apartment

Can hackers enable the camera after the user disabled it?

Why is B♯ higher than C♭ in 31-ET?

How long would it take for people to notice a mass disappearance?

Multi-channel audio upsampling interpolation

If I readied a spell with the trigger "When I take damage", do I have to make a constitution saving throw to avoid losing Concentration?

Where can I go to avoid planes overhead?

Can there be a single technologically advanced nation, in a continent full of non-technologically advanced nations?

Which module had more 'comfort' in terms of living space, the Lunar Module or the Command module?

Getting a W on your transcript for grad school applications

What is the difference between 'unconcealed' and 'revealed'?

Point of the the Dothraki's attack in GoT S8E3?

Position of past participle and extent of the Verbklammer

As matter approaches a black hole, does it speed up?

How does this change to the opportunity attack rule impact combat?

How wide is a neg symbol, how to get the width for alignment?

What happens if you dump antimatter into a black hole?

Can my company stop me from working overtime?



keyerror in formset form field


How do you disable browser Autocomplete on web form field / input tag?JavaScript post request like a form submitDynamically adding a form to a Django formset with AjaxHow to prevent buttons from submitting formsConvert form data to JavaScript object with jQueryHTML-encoding lost when attribute read from input fieldjQuery AJAX submit formWhat does enctype='multipart/form-data' mean?Cannot display HTML stringDjango form. How hidden colon from initial_text?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I am making a delivery note transaction form, I have created a formset for which I want Django to ignore item transactions where the item is not selected and is empty.



forms.py



class Delivery_note_transiction_form(forms.Form):

item = forms.CharField(widget=Select2Widget(attrs="class" : "item"),label=False,required=False)
description = forms.CharField(widget=forms.TextInput(attrs= 'placeholder' : 'optionall','class' : 'description'),label=False,required=False)
quantity = forms.IntegerField(widget=forms.NumberInput(attrs='class' : 'quantity'),label=False,min_value=1)
id = forms.CharField(widget=forms.HiddenInput,required=False)

Delivery_note_transiction_form_formset = forms.formset_factory(Delivery_note_transiction_form,extra=1)


views.py



def feedback(request):
if request.method == "POST" and request.is_ajax():
form = Deliver_Note_Main_Modelform(request.POST)
formset = Delivery_note_transiction_form_formset(request.POST,request.FILES)
if form.is_valid() and formset.is_valid():

ins = form.save(commit=False)
ins.author = request.user

result = Customer_data.objects.get(pk=form.cleaned_data['customer'])

ins.customer_list = result
ins.save()


max_invoice = Invoice_max.objects.get(invoice_name='delivery')
max_invoice.invoice_no = max_invoice.invoice_no + 1
max_invoice.save()

print(formset)
for instant in formset:
if instant.cleaned_data['item']:

item = Product.objects.get(pk=instant.cleaned_data['item'])
description = instant.cleaned_data['description']
quantity = instant.cleaned_data['quantity']
Delivery_Note_Transiction.objects.create(
item=item,
description=description,
quantity=quantity,
delivery_invoice_no=ins
)

return JsonResponse('success':True, 'next' : reverse_lazy('delivery note:delivery note home page'))

else:
return render(request,"delivery_note/ajax/delivery note error message.html","error" : form, "transiction_error": formset)
return HttpResponse("Hello from feedback!")


template.html



% for delivery in delivery_transiction %
<tr class=" delivery_form ">
<td class="col-sm-4"> delivery.item</td>
<td class="col-sm-4">as_crispy_field </td>
<td class="col-sm-4">as_crispy_field </td>
</tr>
% endfor %


The post data is sent by Ajax and the selected option is created on the template. When it is loaded, a new row is added by Ajax. The problem is I want to it ignore transaction entry if the item is not selected or is empty, but when I run it, it gives this error:




"KeyError: 'item'"




It should ignore empty or not selected items. This only happens when the item is not selected in the transaction. I want to fix this error so that it will simply ignore rows in which the item is not selected.










share|improve this question






























    1















    I am making a delivery note transaction form, I have created a formset for which I want Django to ignore item transactions where the item is not selected and is empty.



    forms.py



    class Delivery_note_transiction_form(forms.Form):

    item = forms.CharField(widget=Select2Widget(attrs="class" : "item"),label=False,required=False)
    description = forms.CharField(widget=forms.TextInput(attrs= 'placeholder' : 'optionall','class' : 'description'),label=False,required=False)
    quantity = forms.IntegerField(widget=forms.NumberInput(attrs='class' : 'quantity'),label=False,min_value=1)
    id = forms.CharField(widget=forms.HiddenInput,required=False)

    Delivery_note_transiction_form_formset = forms.formset_factory(Delivery_note_transiction_form,extra=1)


    views.py



    def feedback(request):
    if request.method == "POST" and request.is_ajax():
    form = Deliver_Note_Main_Modelform(request.POST)
    formset = Delivery_note_transiction_form_formset(request.POST,request.FILES)
    if form.is_valid() and formset.is_valid():

    ins = form.save(commit=False)
    ins.author = request.user

    result = Customer_data.objects.get(pk=form.cleaned_data['customer'])

    ins.customer_list = result
    ins.save()


    max_invoice = Invoice_max.objects.get(invoice_name='delivery')
    max_invoice.invoice_no = max_invoice.invoice_no + 1
    max_invoice.save()

    print(formset)
    for instant in formset:
    if instant.cleaned_data['item']:

    item = Product.objects.get(pk=instant.cleaned_data['item'])
    description = instant.cleaned_data['description']
    quantity = instant.cleaned_data['quantity']
    Delivery_Note_Transiction.objects.create(
    item=item,
    description=description,
    quantity=quantity,
    delivery_invoice_no=ins
    )

    return JsonResponse('success':True, 'next' : reverse_lazy('delivery note:delivery note home page'))

    else:
    return render(request,"delivery_note/ajax/delivery note error message.html","error" : form, "transiction_error": formset)
    return HttpResponse("Hello from feedback!")


    template.html



    % for delivery in delivery_transiction %
    <tr class=" delivery_form ">
    <td class="col-sm-4"> delivery.item</td>
    <td class="col-sm-4">as_crispy_field </td>
    <td class="col-sm-4">as_crispy_field </td>
    </tr>
    % endfor %


    The post data is sent by Ajax and the selected option is created on the template. When it is loaded, a new row is added by Ajax. The problem is I want to it ignore transaction entry if the item is not selected or is empty, but when I run it, it gives this error:




    "KeyError: 'item'"




    It should ignore empty or not selected items. This only happens when the item is not selected in the transaction. I want to fix this error so that it will simply ignore rows in which the item is not selected.










    share|improve this question


























      1












      1








      1








      I am making a delivery note transaction form, I have created a formset for which I want Django to ignore item transactions where the item is not selected and is empty.



      forms.py



      class Delivery_note_transiction_form(forms.Form):

      item = forms.CharField(widget=Select2Widget(attrs="class" : "item"),label=False,required=False)
      description = forms.CharField(widget=forms.TextInput(attrs= 'placeholder' : 'optionall','class' : 'description'),label=False,required=False)
      quantity = forms.IntegerField(widget=forms.NumberInput(attrs='class' : 'quantity'),label=False,min_value=1)
      id = forms.CharField(widget=forms.HiddenInput,required=False)

      Delivery_note_transiction_form_formset = forms.formset_factory(Delivery_note_transiction_form,extra=1)


      views.py



      def feedback(request):
      if request.method == "POST" and request.is_ajax():
      form = Deliver_Note_Main_Modelform(request.POST)
      formset = Delivery_note_transiction_form_formset(request.POST,request.FILES)
      if form.is_valid() and formset.is_valid():

      ins = form.save(commit=False)
      ins.author = request.user

      result = Customer_data.objects.get(pk=form.cleaned_data['customer'])

      ins.customer_list = result
      ins.save()


      max_invoice = Invoice_max.objects.get(invoice_name='delivery')
      max_invoice.invoice_no = max_invoice.invoice_no + 1
      max_invoice.save()

      print(formset)
      for instant in formset:
      if instant.cleaned_data['item']:

      item = Product.objects.get(pk=instant.cleaned_data['item'])
      description = instant.cleaned_data['description']
      quantity = instant.cleaned_data['quantity']
      Delivery_Note_Transiction.objects.create(
      item=item,
      description=description,
      quantity=quantity,
      delivery_invoice_no=ins
      )

      return JsonResponse('success':True, 'next' : reverse_lazy('delivery note:delivery note home page'))

      else:
      return render(request,"delivery_note/ajax/delivery note error message.html","error" : form, "transiction_error": formset)
      return HttpResponse("Hello from feedback!")


      template.html



      % for delivery in delivery_transiction %
      <tr class=" delivery_form ">
      <td class="col-sm-4"> delivery.item</td>
      <td class="col-sm-4">as_crispy_field </td>
      <td class="col-sm-4">as_crispy_field </td>
      </tr>
      % endfor %


      The post data is sent by Ajax and the selected option is created on the template. When it is loaded, a new row is added by Ajax. The problem is I want to it ignore transaction entry if the item is not selected or is empty, but when I run it, it gives this error:




      "KeyError: 'item'"




      It should ignore empty or not selected items. This only happens when the item is not selected in the transaction. I want to fix this error so that it will simply ignore rows in which the item is not selected.










      share|improve this question
















      I am making a delivery note transaction form, I have created a formset for which I want Django to ignore item transactions where the item is not selected and is empty.



      forms.py



      class Delivery_note_transiction_form(forms.Form):

      item = forms.CharField(widget=Select2Widget(attrs="class" : "item"),label=False,required=False)
      description = forms.CharField(widget=forms.TextInput(attrs= 'placeholder' : 'optionall','class' : 'description'),label=False,required=False)
      quantity = forms.IntegerField(widget=forms.NumberInput(attrs='class' : 'quantity'),label=False,min_value=1)
      id = forms.CharField(widget=forms.HiddenInput,required=False)

      Delivery_note_transiction_form_formset = forms.formset_factory(Delivery_note_transiction_form,extra=1)


      views.py



      def feedback(request):
      if request.method == "POST" and request.is_ajax():
      form = Deliver_Note_Main_Modelform(request.POST)
      formset = Delivery_note_transiction_form_formset(request.POST,request.FILES)
      if form.is_valid() and formset.is_valid():

      ins = form.save(commit=False)
      ins.author = request.user

      result = Customer_data.objects.get(pk=form.cleaned_data['customer'])

      ins.customer_list = result
      ins.save()


      max_invoice = Invoice_max.objects.get(invoice_name='delivery')
      max_invoice.invoice_no = max_invoice.invoice_no + 1
      max_invoice.save()

      print(formset)
      for instant in formset:
      if instant.cleaned_data['item']:

      item = Product.objects.get(pk=instant.cleaned_data['item'])
      description = instant.cleaned_data['description']
      quantity = instant.cleaned_data['quantity']
      Delivery_Note_Transiction.objects.create(
      item=item,
      description=description,
      quantity=quantity,
      delivery_invoice_no=ins
      )

      return JsonResponse('success':True, 'next' : reverse_lazy('delivery note:delivery note home page'))

      else:
      return render(request,"delivery_note/ajax/delivery note error message.html","error" : form, "transiction_error": formset)
      return HttpResponse("Hello from feedback!")


      template.html



      % for delivery in delivery_transiction %
      <tr class=" delivery_form ">
      <td class="col-sm-4"> delivery.item</td>
      <td class="col-sm-4">as_crispy_field </td>
      <td class="col-sm-4">as_crispy_field </td>
      </tr>
      % endfor %


      The post data is sent by Ajax and the selected option is created on the template. When it is loaded, a new row is added by Ajax. The problem is I want to it ignore transaction entry if the item is not selected or is empty, but when I run it, it gives this error:




      "KeyError: 'item'"




      It should ignore empty or not selected items. This only happens when the item is not selected in the transaction. I want to fix this error so that it will simply ignore rows in which the item is not selected.







      javascript python html ajax django






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 23 at 0:21









      MarredCheese

      3,34612340




      3,34612340










      asked Mar 22 at 22:21









      HamidHamid

      613




      613






















          1 Answer
          1






          active

          oldest

          votes


















          1














          You have to use a try except when searching a dictionary for a key.



          for instant in formset:
          try:
          item = Product.objects.get(pk=instant.cleaned_data['item'])
          Except KeyError:
          # What to do if no 'item'.


          You will have to figure out where to put the rest of your code, but this will get you past the KeyError.






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55308515%2fkeyerror-in-formset-form-field%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            You have to use a try except when searching a dictionary for a key.



            for instant in formset:
            try:
            item = Product.objects.get(pk=instant.cleaned_data['item'])
            Except KeyError:
            # What to do if no 'item'.


            You will have to figure out where to put the rest of your code, but this will get you past the KeyError.






            share|improve this answer



























              1














              You have to use a try except when searching a dictionary for a key.



              for instant in formset:
              try:
              item = Product.objects.get(pk=instant.cleaned_data['item'])
              Except KeyError:
              # What to do if no 'item'.


              You will have to figure out where to put the rest of your code, but this will get you past the KeyError.






              share|improve this answer

























                1












                1








                1







                You have to use a try except when searching a dictionary for a key.



                for instant in formset:
                try:
                item = Product.objects.get(pk=instant.cleaned_data['item'])
                Except KeyError:
                # What to do if no 'item'.


                You will have to figure out where to put the rest of your code, but this will get you past the KeyError.






                share|improve this answer













                You have to use a try except when searching a dictionary for a key.



                for instant in formset:
                try:
                item = Product.objects.get(pk=instant.cleaned_data['item'])
                Except KeyError:
                # What to do if no 'item'.


                You will have to figure out where to put the rest of your code, but this will get you past the KeyError.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 23 at 9:37









                Carl BrubakerCarl Brubaker

                675213




                675213





























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55308515%2fkeyerror-in-formset-form-field%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                    은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현