skip to Main Content

I have one view displaying a form. Now, depending on the button the user chooses, I want to have the data processed in a different way. These "different ways" correspond with different views that I want the POST request go to.

Please help me building a form with multiple buttons leading to different urls/views.

<form action="/your-name/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Process form with view ONE">
    <input type="submit" value="Process form with view TWO">
    <input type="submit" value="Process form with view THREE">
</form>

My problem here is that the action attribute of the form tag defines where this POST request is going to. How can I change that target url via multiple buttons?

I know I could also handle this logic on the server-side. But the question is: Do I have to? If not, please show me the way

2

Answers


  1. you can use ajax with onclick attribute. post_url as an argument like this

    <form method="post">
        {% csrf_token %}
        {{ form }}
        <input type="submit" value="Process form with view ONE" onclick='testFun(url_one)'>
        <input type="submit" value="Process form with view TWO" onclick='testFun(url_two)'>
        <input type="submit" value="Process form with view THREE" onclick='testFun(url_three)'>
    </form>
    
    Login or Signup to reply.
  2. To handle this on the frontend without even using ajax, you can use JavaScript to change the action URL of the form based on which button is clicked before submitting the form.

    Slight change on your HTML code

    <form method="post" id="my-form">
        {% csrf_token %}
        {{ form }}
        <input type="submit" id="view1" value="Process form with view ONE">
        <input type="submit" id="view2" value="Process form with view TWO">
        <input type="submit" id="view3" value="Process form with view THREE">
    </form>
    

    JavaScript for handling the redirection of the form based the button clicked

    const form = document.getElementById('my-form');
    const button1 = document.getElementById('view1');
    const button2 = document.getElementById('view2');
    const button3 = document.getElementById('view3');
    
    button1.addEventListener('click', () => {
      form.action = '/view1/';
    });
    
    button2.addEventListener('click', () => {
      form.action = '/view2/';
    });
    
    button3.addEventListener('click', () => {
      form.action = '/view3/';
    });
    
    // Submit the form
    form.submit();
    

    Note: You can use jQuery for better code optimization

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search