0

My template contents multiple forms with multiple buttons.

I've read these topics:

Proper way to handle multiple forms on one page in Django

How can I build multiple submit buttons django form?

How can I access the form submit button value in Django?

and I did exactly the same, included "name" and "value" in form's input (tried with button tag too)

but the "name" attribute doesn't exist in POST request. What am i doing wrong?

template:

<div class="container" align="center" style="border: solid 3px red">
    <h3>Form 1</h3>
    <form id="form_step_1" method="post" action="{% url 'ajax_order_data' %}" align="center">
            {% csrf_token %}
            {{ FormStep1 }}
            <button type="submit" name="step_1" value="step_1">button_step1</button>
    </form>
</div>

<br>

<div class="container" align="center"  style="border: solid 3px red">
    <h3>Form 2</h3>
    <form id="form_step_2" method="post" action="{% url 'ajax_order_data' %}" align="center">
            {% csrf_token %}
            {{ FormStep2 }}
            <button type="submit" name="step_2" value="step_2">button_step2</button>
    </form>
</div>

<script>
    var form_1 = $("#form_step_1");
    var form_2 = $("#form_step_2");

    form_1.submit(function(e){
        e.preventDefault();
        var url = $(form_1).attr('action');
        $.ajax({
          type: 'POST',
          url: url,
          data: form_1.serialize(),
          dataType: 'json',
          success: function (data) {smth_1}
        })
    });

    form_2.submit(function(e){
        e.preventDefault();
        var url = $(form_2).attr('action');
        $.ajax({
          type: 'POST',
          url: url,
          data: form_2.serialize(),
          dataType: 'json',
          success: function (data) {smth_2}
        })
    });
</script>

view:

def somefunc(request):
if request.method == 'POST':
    if 'step_1' in request.POST:
Usoboi
  • 23
  • 4

1 Answers1

2

You've explicitly disabled the normal form submission process, and are sending the data as JSON in your Ajax. So you can't use the normal methods of handling form-encoded data in Django, because you haven't got any.

Instead, you need to deserialise the body of the request, which will give you a dict:

data = json.loads(request.body)
if 'step_1' in data:
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895