Home > OS >  Differentiate which button was used to submit form Django/JS
Differentiate which button was used to submit form Django/JS

Time:12-10

I have a Django view of a form that presents the user with two options. On form submission, one Button will send them to one view, the other will send them to another. This is the part of that view:

form = MenuItemForm(request.POST or None, request.FILES or None)
if request.method != 'POST':
    # No data submitted; create a blank form.
    form = MenuItemForm()
else:
    if 'add_ingredients' in request.POST:
        # POST data submitted; process data.
        if form.is_valid():
            menu_item = form.save(commit=False)
            menu_item.menu = menu_instance
            menu_item.save()
            return redirect('core:add_ingredient', menu_item_id=menu_item.id)
    else:
        # POST data submitted; process data.
        if form.is_valid():
            menu_item = form.save(commit=False)
            menu_item.menu = menu_instance
            menu_item.save()
            return redirect('core:edit_menu')

This worked fine on its own. Here are the form and buttons in the template:

      <form id="form"  method="post" action="{% url 'core:add_ingredient' menu_item.id %}">
                {% csrf_token %}
                {{ form.as_p }}
                <div >
                    <button id="another-ingredient-button" type="submit" name="add_ingredient">Add Another Ingredient</button>
                    <button type="submit" name="substitute">Add Substitute</button>
                    <button  type="submit" name="done">Done</button>
                </div>
            </form>

After I added the code below, the form still submits, but it doesnt recognize which button was clicked that submitted the form, and always sends me to one view, I thought about adding an eventListener to each button but then the my alert box and the other code runs even when the form doesn't submit. Any help would be appreciated!

const alertBox = document.getElementById('alert-box')
const anotherIngredientButton = document.getElementById('another-ingredient-button')
const form = document.getElementById('form')

let formSubmitted = false;

form.addEventListener('submit', (e) => {
   e.preventDefault()
   alertBox.style.display = 'block';
   console.log(form)

   setTimeout(() => {
    form.submit()
    alertBox.style.display = 'none'
    formSubmitted = true
}, 1000)

});

CodePudding user response:

You can add a value attribute to your button:

<button type="submit" name="button_type" value="add_ingredient">Add Another Ingredient</button>
<button type="submit" name="button_type" value="substitute">Substitute</button>
<button type="submit" name="button_type" value="done">Done</button>

and in your view:

if request.POST.get("button_type") == "add_ingredient":
    ...
elif request.POST.get("button_type") == "substitute":
    ...
elif request.POST.get("button_type") == "done":
    ...
  • Related