Django - How to distinguish which button was clicked?

Asked

Viewed 778 times

3

In my application’s search template I have 3 tags <button>, one to search, the other to edit and the other to delete:

<button class="btn btn-lg btn-primary" type="submit" id="buscar" name="buscar">Buscar</button>
<button class="btn btn-lg btn-primary" type="submit" id="editar" name="editar">Editar</button>
<button class="btn btn-lg btn-primary" type="submit" id="apagar" name="apagar">Apagar</button>

Being in the same template, as I do for Django to make the distinction between <buttons>, so that depending on the button clicked the correct view is executed ?!

Ex: If I click the delete button it will delete the item the search located.

1 answer

3


To my knowledge, if you have several buttons in the same form you can not submit this form to different pages unless you use Javascript to change the action of form. What you can do is have a generic view that "routes" the call to a different view depending on which button was clicked.

def view_generica(request, *args, **kwargs):
    view_certa = None

    if request.GET['buscar']:
        view_certa = uma_view
    elif request.GET['editar']:
        view_certa = outra_view
    elif request.GET['apagar']:
        view_certa = terceira_view
    else
        return HttpResponse("Erro")

    return view_certa(request, *args, **kwargs)

Note: the code to deal with the specific button that was clicked came of that reply in Soen. I haven’t tested it, so I can’t say for sure if it works in practice.

Another alternative is to use common links (a) instead of buttons, and style them to look like buttons. In that case, you must correctly assign the href in your template to load the view with the right parameters (i.e. identifying the item located in your search).

Finally, you can create a form different for each button, assigning the action according. If the data returned by your template is immutable, it may be a good option. Each form then repeat the data (identification) of the returned item, in a Hidden input for example (to be sent to the view next to the form submission).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.