javascriptjquerydjangodjango-formsdjango-views

How to update a hidden form field? (Django)


I am trying to figure out the best approach to modifying a hidden django form field. Or if it's even possible. I had my HTML setup to accomplish this very task and it was working perfectly. However, in order to prevent multiple submissions I had to change my HTML and now I am unable to figure out how to pass a value via an HTML button depending on what the user clicks on.

Previously, I had two buttons defined as outline below:

<button type="submit" class="button1" name="status" value="Saved"><h3 class="txtalgn4">Save</h3></button>

<button type="submit" class="button2" name="status" value="Submitted"><h3 class="txtalgn4">Submit</h3></button>

As stated above, this worked perfectly for the purpose of passing a value to an attribute for my model. The value of status was saved as expected depending on which button the user clicked on.

Now I have updated the buttons to type="button" in response to this issue that I opened up today...How To Prevent Double Submit With Form Validation

I tried using the following code:

<button type="button" class="button1" name="status" value="Saved"><h3 class="txtalgn4">Save</h3></button>

<button type="button" class="button2" name="status" value="Submitted"><h3 class="txtalgn4">Submit</h3></button>

And then I also changed the status field to {{ status.as_hidden }} in my HTML to get the value. This only works if I hardcode the status value in my database structure. I need to be able to get this value dynamically depending on what the user clicks. Is JQuery with Ajax the right approach for this? Is there some simple way to modify the hidden field depending on which button the user clicks?

Is there some better way to go about trying to get this field in a hidden manner? As stated above the HTML way with type="submit" worked perfectly, but caused problems when I was trying to prevent the user from double submitting the form. As in all things programming I solved one problem and created another.

Thanks in advance for any thoughts.


Solution

  • Keep using two submit buttons like you were. But instead of disabling the buttons, you disable the whole form from submitting if once submitted.

    First, give your form a unique html ID.

    <form id="myform">
        ...
    </form>
    
    <!-- JS code -->
    <script type="text/javascript">
    $('#myform').on('submit', function(e) {
        if ($(this).hasClass('submitted')) {
            // prevent submission
            e.preventDefault();
            return;
        }
    
        $(this).addClass('submitted');
    });
    </script>