user16503887
user16503887

Reputation:

How to delete model data on button click? - Django

I have the following button: <a style="float:right; margin:5px; color: white;" href="" class="btn btn-success" >Accept</a>

When the button is clicked on by the user, I want to delete data that is associated with the pk

For example, when the button is clicked, I want to pass the {{donation.pk}} into a function and delete the Donation that is associated with it

I have done so much research but I can not find out a way to do this.

Upvotes: 1

Views: 793

Answers (1)

Biplove Lamichhane
Biplove Lamichhane

Reputation: 4095

First you have to understand that the tag you are using is client side which means client can access that easily. And, another part of the web development is server side which is exact opposite. Or, it is the scripts (lets say) which only server have access. In your case, your computer is hosting the localhost:8000 from your local server and the server is django's default server.

Now, we have understand two main parts, it will be easy to break things down. What you are wanting is to delete the donation with id, which is in the backend or which is in our database. And, database are only access through server in our case, django will communicate with the database.

So, to delete the donation, you will send request to server to ask for deletion of donation. To send that request you have many methods like GET, POST, PUT and so on. In our case we will go with GET.

Firstly your client side will be able to send request with:

<a style="float:right; margin:5px; color: white;" href="/donations/{{donation.pk}}/delete/" class="btn btn-success" >Accept</a>

Now, we will make a path or route in urls.py. Like:

from . import views

urlpatterns = [
    path('donations/', views.donations, name='donations'),
    path('donations/<str:id>/delete/', views.deleteDonation, name='delete_donations'),
    path('donations/<str:id>/edit/', views.editDonation, name='edit_donations'),
]

After we have made urlpatterns, when we click on the link of a tag, it will go to the route which is matched (in our case, it is second route) and then, it will go the the function in our views directory.

views.py

.....
from django.shortcuts import get_object_or_404
from django.shortcuts import render

def deleteDonation(request, id=None):
    donation = get_object_or_404(Donation, pk=id)
    donation.delete()
    return render(request, "delete_your_donation_.html") 

Upvotes: 1

Related Questions