简体   繁体   中英

How to submit a form with django ajax without parsing the input

I have a modal form that I use when users need to create something without leaving the page they are on. And to avoid refreshing the page after the modal form submission, I am using ajax to submit the form.

For a series of reasons, I can't parse the form field by field so I was trying to find a way to get all the form data and submit them with a "general" approach and then process the post-request in my view (populate the form with the POST).

However, the approach I am using is not working and I was hoping someone had an alternative idea.

 <body>
    <!--Modal -->
    <div class="modal fade" tabindex="-1" role="dialog" id="modal">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
                <!-- Popup -->
                <div class="pop-up-form">
                    <div class="pop-up-form__wrp">

                        <!-- Title -->
                        <div class="pop-up-form__title-wrp">
                            <h2 class="pop-up-form__title">Create New</h2>
                        </div>
                        <!-- END Title -->

                        <!-- Form -->
                        <form class="pop-up-form__form" id="form">
                            {% csrf_token %}
                            {% for field in form %}
                                <div class="pop-up-form__input-wrp">
                                    <label class="pop-up-form__label" for="{{ field.id_for_label }}">{{ field.label }}</label>
                                    {{ field|add_class:"pop-up-form__input" }}
                                    {% for error in field.errors %}
                                      <p class="help-block">{{ error }}</p>
                                    {% endfor %}
                                </div>
                            {% endfor %}
                        <!--
                        <div class="form-group{#% if field.errors %#}invalid{#% endif %#}"></div>
                        -->
                             <!-- BTNs -->
                            <div class="pop-up-form__btn-wrp">
                                <button data-dismiss="modal" class="btn-transparent">Close</button>
                                <button type="submit" form='form' class="btn-black">Save</button>
                            </div>
                            <!-- END BTNs -->
                        </form>
                        <!-- END Form -->

                    </div>
                </div>
                <!-- END Popup -->
          </div>
        </div>
    </div>
    <!--Modal -->
     </body>


<script> 
  $('#form').on('submit', function(e){

            e.preventDefault();
            console.log('I am getting called')
            $.ajax({
                    type: "POST",
                    url: "{{ post }}",
                    data: {
                        csrfmiddlewaretoken: "{{ csrf_token }}",
                        'data': $('form').serialize(),
                    },
                    success: function(response) {
                        console.log('success updated')
                        console.log(response)
                    }
                  });
        })
</script>

I solved this changing approach. Here is the final html and js I am using as well as the code on the views to deserealize the serealized data.

 <body>
    <!--Modal -->
    <div class="modal fade" tabindex="-1" role="dialog" id="{{ modal_id }}">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
                <!-- Popup -->
                <div class="pop-up-form">
                    <div class="pop-up-form__wrp">

                        <!-- Title -->
                        <div class="pop-up-form__title-wrp">
                            <h2 class="pop-up-form__title">Create New</h2>
                        </div>
                        <!-- END Title -->

                        <!-- Form -->
                        <form class="pop-up-form__form" id="modalform">
                            {% csrf_token %}
                            {% for field in form %}
                                <div class="pop-up-form__input-wrp">
                                    <label class="pop-up-form__label" for="{{ field.id_for_label }}">{{ field.label }}</label>
                                    {{ field|add_class:"pop-up-form__input" }}
                                    {% for error in field.errors %}
                                      <p class="help-block">{{ error }}</p>
                                    {% endfor %}
                                </div>
                            {% endfor %}
                        <!--
                        <div class="form-group{#% if field.errors %#}invalid{#% endif %#}"></div>
                        -->
                             <!-- BTNs -->
                            <div class="pop-up-form__btn-wrp">
                                <button data-bs-dismiss="{{ modal_id }}" class="btn-transparent">Close</button>
                                <button type="submit" form='modalform' class="btn-black">Save</button>
                            </div>
                            <!-- END BTNs -->
                        </form>
                        <!-- END Form -->

                    </div>
                </div>
                <!-- END Popup -->
          </div>
        </div>
    </div>
    <!--Modal -->
     </body>
<script>
        $('#modalform').on('submit', function(e){
            e.preventDefault();
            $.ajax({
                    type: "POST",
                    url: "{{ post }}",
                    data: {
                        csrfmiddlewaretoken: "{{ csrf_token }}",
                        'data': $('#modalform').serialize(),
                    },
                    success: function(response) {
                        console.log('success updated')
                        console.log(response)
                        $('{{update_id}}').selectize()[0].selectize.addOption(
                            [{'id': response['id'], 'title_name': response['title_name']}]
                        )
                        $('{{ update_id }}')[0].selectize.addItem(response['id']);
                         $("#{{ modal_id }}").modal('toggle');
                    }
                  });
        })
    </script>
 form_data = QueryDict(request.POST['data'].encode('ASCII'))  # Query strings use only ASCII code points so it is safe.
        title_form = TitleModalForm(form_data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM