I overrode the clean() method in my django form, and fixed a bug that arose. But I dont understand how the...





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







0















I am trying to add some validation into a form.




  • Validation 1: quantity_moved should be above 0.

  • Validation 2: source and destination must be different

  • Validation 3: quantity_moved must be lower than the quantity at source location.


Buggy Code



# NOTE: Overriding the default method
def clean(self):
cleaned_data = super().clean()
source = str(cleaned_data['source'])
destination = str(cleaned_data['destination'])
quantity_moved = cleaned_data['quantity_moved']
item = cleaned_data['item']

# Checking if the source and destination are same
if destination == source:
msg = 'エラー:移動先と移動元が同じです。'
self.add_error('source', msg)
self.add_error('destination', msg)

# Checking if the quantity to move is more than the current stock at the source location
max_qty = ActualStock.objects.filter(item=item, location=cleaned_data['source'])[0].current_stock
print(">" * 80, max_qty)

if quantity_moved > max_qty:
msg = "エラー:移動元に商品の数は足りません。現在, {0}に {1}の数は {2} です。".format(source, item, max_qty)
self.add_error('quantity_moved', msg)
return cleaned_data


Now, during testing if i enter same values for both source and destination(both are selected from respective dropdowns which points a same table in DB), I get a KeyError.



Now, if I change the order of the checks that I am performing as shown below, the code works.



Working Code:



# NOTE: Overriding the default method
def clean(self):
cleaned_data = super().clean()
source = str(cleaned_data['source'])
destination = str(cleaned_data['destination'])
quantity_moved = cleaned_data['quantity_moved']
item = cleaned_data['item']

# Checking if the quantity to move is more than the current stock at the source location
max_qty = ActualStock.objects.filter(item=item, location=cleaned_data['source'])[0].current_stock
print(">" * 80, max_qty)

if quantity_moved > max_qty:
msg = "エラー:移動元に商品の数は足りません。現在, {0}に {1}の数は {2} です。".format(source, item, max_qty)
self.add_error('quantity_moved', msg)


# Checking if the source and destination are same
if destination == source:
msg = 'エラー:移動先と移動元が同じです。'
self.add_error('source', msg)
self.add_error('destination', msg)

return cleaned_data


Like I said, I managed to fix the bug but do not understand what fixed the bug here. Wondering if someone could shed some light.










share|improve this question





























    0















    I am trying to add some validation into a form.




    • Validation 1: quantity_moved should be above 0.

    • Validation 2: source and destination must be different

    • Validation 3: quantity_moved must be lower than the quantity at source location.


    Buggy Code



    # NOTE: Overriding the default method
    def clean(self):
    cleaned_data = super().clean()
    source = str(cleaned_data['source'])
    destination = str(cleaned_data['destination'])
    quantity_moved = cleaned_data['quantity_moved']
    item = cleaned_data['item']

    # Checking if the source and destination are same
    if destination == source:
    msg = 'エラー:移動先と移動元が同じです。'
    self.add_error('source', msg)
    self.add_error('destination', msg)

    # Checking if the quantity to move is more than the current stock at the source location
    max_qty = ActualStock.objects.filter(item=item, location=cleaned_data['source'])[0].current_stock
    print(">" * 80, max_qty)

    if quantity_moved > max_qty:
    msg = "エラー:移動元に商品の数は足りません。現在, {0}に {1}の数は {2} です。".format(source, item, max_qty)
    self.add_error('quantity_moved', msg)
    return cleaned_data


    Now, during testing if i enter same values for both source and destination(both are selected from respective dropdowns which points a same table in DB), I get a KeyError.



    Now, if I change the order of the checks that I am performing as shown below, the code works.



    Working Code:



    # NOTE: Overriding the default method
    def clean(self):
    cleaned_data = super().clean()
    source = str(cleaned_data['source'])
    destination = str(cleaned_data['destination'])
    quantity_moved = cleaned_data['quantity_moved']
    item = cleaned_data['item']

    # Checking if the quantity to move is more than the current stock at the source location
    max_qty = ActualStock.objects.filter(item=item, location=cleaned_data['source'])[0].current_stock
    print(">" * 80, max_qty)

    if quantity_moved > max_qty:
    msg = "エラー:移動元に商品の数は足りません。現在, {0}に {1}の数は {2} です。".format(source, item, max_qty)
    self.add_error('quantity_moved', msg)


    # Checking if the source and destination are same
    if destination == source:
    msg = 'エラー:移動先と移動元が同じです。'
    self.add_error('source', msg)
    self.add_error('destination', msg)

    return cleaned_data


    Like I said, I managed to fix the bug but do not understand what fixed the bug here. Wondering if someone could shed some light.










    share|improve this question

























      0












      0








      0








      I am trying to add some validation into a form.




      • Validation 1: quantity_moved should be above 0.

      • Validation 2: source and destination must be different

      • Validation 3: quantity_moved must be lower than the quantity at source location.


      Buggy Code



      # NOTE: Overriding the default method
      def clean(self):
      cleaned_data = super().clean()
      source = str(cleaned_data['source'])
      destination = str(cleaned_data['destination'])
      quantity_moved = cleaned_data['quantity_moved']
      item = cleaned_data['item']

      # Checking if the source and destination are same
      if destination == source:
      msg = 'エラー:移動先と移動元が同じです。'
      self.add_error('source', msg)
      self.add_error('destination', msg)

      # Checking if the quantity to move is more than the current stock at the source location
      max_qty = ActualStock.objects.filter(item=item, location=cleaned_data['source'])[0].current_stock
      print(">" * 80, max_qty)

      if quantity_moved > max_qty:
      msg = "エラー:移動元に商品の数は足りません。現在, {0}に {1}の数は {2} です。".format(source, item, max_qty)
      self.add_error('quantity_moved', msg)
      return cleaned_data


      Now, during testing if i enter same values for both source and destination(both are selected from respective dropdowns which points a same table in DB), I get a KeyError.



      Now, if I change the order of the checks that I am performing as shown below, the code works.



      Working Code:



      # NOTE: Overriding the default method
      def clean(self):
      cleaned_data = super().clean()
      source = str(cleaned_data['source'])
      destination = str(cleaned_data['destination'])
      quantity_moved = cleaned_data['quantity_moved']
      item = cleaned_data['item']

      # Checking if the quantity to move is more than the current stock at the source location
      max_qty = ActualStock.objects.filter(item=item, location=cleaned_data['source'])[0].current_stock
      print(">" * 80, max_qty)

      if quantity_moved > max_qty:
      msg = "エラー:移動元に商品の数は足りません。現在, {0}に {1}の数は {2} です。".format(source, item, max_qty)
      self.add_error('quantity_moved', msg)


      # Checking if the source and destination are same
      if destination == source:
      msg = 'エラー:移動先と移動元が同じです。'
      self.add_error('source', msg)
      self.add_error('destination', msg)

      return cleaned_data


      Like I said, I managed to fix the bug but do not understand what fixed the bug here. Wondering if someone could shed some light.










      share|improve this question














      I am trying to add some validation into a form.




      • Validation 1: quantity_moved should be above 0.

      • Validation 2: source and destination must be different

      • Validation 3: quantity_moved must be lower than the quantity at source location.


      Buggy Code



      # NOTE: Overriding the default method
      def clean(self):
      cleaned_data = super().clean()
      source = str(cleaned_data['source'])
      destination = str(cleaned_data['destination'])
      quantity_moved = cleaned_data['quantity_moved']
      item = cleaned_data['item']

      # Checking if the source and destination are same
      if destination == source:
      msg = 'エラー:移動先と移動元が同じです。'
      self.add_error('source', msg)
      self.add_error('destination', msg)

      # Checking if the quantity to move is more than the current stock at the source location
      max_qty = ActualStock.objects.filter(item=item, location=cleaned_data['source'])[0].current_stock
      print(">" * 80, max_qty)

      if quantity_moved > max_qty:
      msg = "エラー:移動元に商品の数は足りません。現在, {0}に {1}の数は {2} です。".format(source, item, max_qty)
      self.add_error('quantity_moved', msg)
      return cleaned_data


      Now, during testing if i enter same values for both source and destination(both are selected from respective dropdowns which points a same table in DB), I get a KeyError.



      Now, if I change the order of the checks that I am performing as shown below, the code works.



      Working Code:



      # NOTE: Overriding the default method
      def clean(self):
      cleaned_data = super().clean()
      source = str(cleaned_data['source'])
      destination = str(cleaned_data['destination'])
      quantity_moved = cleaned_data['quantity_moved']
      item = cleaned_data['item']

      # Checking if the quantity to move is more than the current stock at the source location
      max_qty = ActualStock.objects.filter(item=item, location=cleaned_data['source'])[0].current_stock
      print(">" * 80, max_qty)

      if quantity_moved > max_qty:
      msg = "エラー:移動元に商品の数は足りません。現在, {0}に {1}の数は {2} です。".format(source, item, max_qty)
      self.add_error('quantity_moved', msg)


      # Checking if the source and destination are same
      if destination == source:
      msg = 'エラー:移動先と移動元が同じです。'
      self.add_error('source', msg)
      self.add_error('destination', msg)

      return cleaned_data


      Like I said, I managed to fix the bug but do not understand what fixed the bug here. Wondering if someone could shed some light.







      python django debugging override






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 29 '18 at 1:33









      bibekbibek

      76249




      76249
























          1 Answer
          1






          active

          oldest

          votes


















          2














          From the Django docs:




          Note that add_error() automatically removes the field from cleaned_data.




          So in your first code sample, if destination equals source, you call add_error on both source and destination, and when you want to get source from cleaned_data as follows:



          max_qty = ActualStock.objects.filter(item=item, location=cleaned_data['source'])[0].current_stock


          You get a key error because source key was removed from cleaned_data



          In your second sample you try to get source before calling add_error on it. You can solve this issue more reliably by changing this line of code



          max_qty = ActualStock.objects.filter(item=item, location=cleaned_data['source'])[0].current_stock


          To this:



          max_qty = ActualStock.objects.filter(item=item, location=source)[0].current_stock





          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%2f53530602%2fi-overrode-the-clean-method-in-my-django-form-and-fixed-a-bug-that-arose-but%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









            2














            From the Django docs:




            Note that add_error() automatically removes the field from cleaned_data.




            So in your first code sample, if destination equals source, you call add_error on both source and destination, and when you want to get source from cleaned_data as follows:



            max_qty = ActualStock.objects.filter(item=item, location=cleaned_data['source'])[0].current_stock


            You get a key error because source key was removed from cleaned_data



            In your second sample you try to get source before calling add_error on it. You can solve this issue more reliably by changing this line of code



            max_qty = ActualStock.objects.filter(item=item, location=cleaned_data['source'])[0].current_stock


            To this:



            max_qty = ActualStock.objects.filter(item=item, location=source)[0].current_stock





            share|improve this answer




























              2














              From the Django docs:




              Note that add_error() automatically removes the field from cleaned_data.




              So in your first code sample, if destination equals source, you call add_error on both source and destination, and when you want to get source from cleaned_data as follows:



              max_qty = ActualStock.objects.filter(item=item, location=cleaned_data['source'])[0].current_stock


              You get a key error because source key was removed from cleaned_data



              In your second sample you try to get source before calling add_error on it. You can solve this issue more reliably by changing this line of code



              max_qty = ActualStock.objects.filter(item=item, location=cleaned_data['source'])[0].current_stock


              To this:



              max_qty = ActualStock.objects.filter(item=item, location=source)[0].current_stock





              share|improve this answer


























                2












                2








                2







                From the Django docs:




                Note that add_error() automatically removes the field from cleaned_data.




                So in your first code sample, if destination equals source, you call add_error on both source and destination, and when you want to get source from cleaned_data as follows:



                max_qty = ActualStock.objects.filter(item=item, location=cleaned_data['source'])[0].current_stock


                You get a key error because source key was removed from cleaned_data



                In your second sample you try to get source before calling add_error on it. You can solve this issue more reliably by changing this line of code



                max_qty = ActualStock.objects.filter(item=item, location=cleaned_data['source'])[0].current_stock


                To this:



                max_qty = ActualStock.objects.filter(item=item, location=source)[0].current_stock





                share|improve this answer













                From the Django docs:




                Note that add_error() automatically removes the field from cleaned_data.




                So in your first code sample, if destination equals source, you call add_error on both source and destination, and when you want to get source from cleaned_data as follows:



                max_qty = ActualStock.objects.filter(item=item, location=cleaned_data['source'])[0].current_stock


                You get a key error because source key was removed from cleaned_data



                In your second sample you try to get source before calling add_error on it. You can solve this issue more reliably by changing this line of code



                max_qty = ActualStock.objects.filter(item=item, location=cleaned_data['source'])[0].current_stock


                To this:



                max_qty = ActualStock.objects.filter(item=item, location=source)[0].current_stock






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 29 '18 at 8:27









                Ozgur AkcaliOzgur Akcali

                1,8561430




                1,8561430
































                    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%2f53530602%2fi-overrode-the-clean-method-in-my-django-form-and-fixed-a-bug-that-arose-but%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

                    A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

                    Calculate evaluation metrics using cross_val_predict sklearn

                    Insert data from modal to MySQL (multiple modal on website)