Django - How to distinguish which button was clicked?

3

In the search template of my application I have 3 <button> tags, one to search, the other to edit and one 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, how do I make Django distinguish between <buttons> , so depending on which button clicked the correct view is executed?!

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

    
asked by anonymous 27.05.2014 / 20:01

1 answer

3

As far as I know, if you have multiple buttons on 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 to 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 handle the specific button that was clicked that response in SOen . I have not tested it, so I can not say for sure if it works in practice.

Another alternative is to use common links ( a ) instead of buttons, and stylize them to look like buttons . In this case, you have to 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 action accordingly. If the data returned by your template is immutable, it may be a good choice. Each form would then repeat the data (id) of the returned item in a hidden input for example (in order to be sent to the view next to the submission of the form).

    
27.05.2014 / 20:13