Home > other >  Distinguish which link-button clicked in django
Distinguish which link-button clicked in django

Time:10-25

I have that html code:

<form id="my-form" method="POST" action="{% url 'my_view' %}">
  {% csrf_token %}
  <div class="row">
    <div class="col-md-6">
      <div class="md-form mb-1">
        <textarea id="message" name="message" rows="2" class="form-control md-textarea"></textarea>
      </div>
    </div>
    <div class="col-md-6">
      <div class="md-form mb-1">
        <textarea id="message_then" name="message_then" rows="2" class="form-control md-textarea"></textarea>
      </div>
    </div>
  </div>

<div class="text-center text-md-left">
  <a class="btn btn-primary" onclick="document.getElementById('my-form').submit();" style="width: 78px;" name="name1">Click1</a>
</div>
<div class="text-center text-md-left">
  <a class="btn btn-primary" onclick="document.getElementById('my-form').submit();" style="width: 78px;" name="name2">Click2</a>
</div>

</form>

Now I would like to get to know which "button" was clicked. Unfortunately request.POST doesn't have that information.

CodePudding user response:

You should add another field to specify which button has been clicked.

Exp: Add this to your form then update your "a" elements onclick event code like this:

<a class="btn btn-primary" onclick="update_form(this)" style="width: 78px;">Click1</a>

And finally some js code to update the form

<script>
 function update_form(button){
     document.getElementById("id_button").value = document.getElementById(button).innerText;
     document.getElementById('my-form').submit();
 }
</script>

In your django view use this to get the selected button: request.POST['id_button']

  • Related