How delete a record on button click using Django?

Viewed 31

I am trying to delete a record in a database when a yes button is clicked using django.

views.py

def deleteServer(request, server_id):
    server = Server.objects.get(pk=server_id)
    print(request.POST)
    if request.POST.get('yesBtn'):
       server.delete()
       return HttpResponseRedirect('homepage')
    elif request.POST.get('noBtn'):
       return HttpResponseRedirect('homepage')
    return render(request, 'deleteServer.html', {'value': request.POST})

deleteServer.html

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
   <title>Cancella server</title>
  </head>
  <body>
     <button onclick="document.getElementById('id01').style.display='block'"
   class="w3-button">Cancella server</button>

   <!-- The Modal -->
   <div id="id01" class="w3-modal">
     <div class="w3-modal-content">
       <div class="w3-container">
         <span onclick="document.getElementById('id01').style.display='none'"
    class="w3-button w3-display-topright">&times;</span>
        <p>Vuoi davvero cancellare il server selezionato?</p>
        <a href="{% url 'homepage' %}" type="button" name="yesBtn" class="btn btn-success">SI</a>
        <a href="{% url 'homepage' %}" type="button" name="noBtn" class="btn btn-danger">NO</a>
     </div>
    </div>
  </div>
</body>
</html>

When I click on the yes button the record is not deleted. I thought the problem is in the deleteServer function in the file views.py.

EDIT

I printed the results of request.GET and the output is QueryDict = {}

1 Answers

You just have to pass the values in the GET.. Normally it's like ?key=value and if you have multiple its ?key0=value0&key1=value1

<a href="{% url 'homepage' %}?yesBtn=True" type="button" name="yesBtn" class="btn btn-success">SI</a>
<a href="{% url 'homepage' %}?noBtn=True" type="button" name="noBtn" class="btn btn-danger">NO</a>

Note: the =True doesn't matter, It could be literally anything because in the view it just looks ~"Is key in GET" and doesn't actually look at the value itself


Edit

I completely missed that your view used request.POST.get(x)
It should use request.GET.get(x)

def deleteServer(request, server_id):
    server = Server.objects.get(pk=server_id)

    print('POST:', request.POST)
    print('GET:', request.GET)

    if request.GET.get('yesBtn'):
       server.delete()
       return HttpResponseRedirect('homepage')
    elif request.GET.get('noBtn'):
       return HttpResponseRedirect('homepage')

    return render(request, 'deleteServer.html', {'value': request.POST})
Related