How to delete model by filtering with pk

I am trying to delete an entire model using pk, but when I click on "delete" I am redirected to the given page but nothing happens model is still there and not being deleted, but when I write the ‘room_name’ instead of ‘pk’ it does work, (thanks in advance)

def delete_room(request, pk):
    return redirect('home')
    path("delete/<int:pk>/", views.delete_room, name="delete_room")
class Room(models.Model):
    name = models.CharField(max_length=100)
    about = models.TextField(max_length=500, null=True, blank=True)
    creator = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='room_creator')
    members = models.ManyToManyField(User, through="RoomMember")
class RoomMember(models.Model):
    approved = models.BooleanField(default=False, blank=False)
    room = models.ForeignKey(Room, related_name='memberships', on_delete=models.CASCADE)
    user = models.ForeignKey(User, related_name='user_groups', on_delete=models.CASCADE)
class Messages(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False)
    text = models.CharField(max_length=10000, blank=False, null=False)
    date = models.DateTimeField(
    room = models.ForeignKey(Room, null=True, blank=False, on_delete=models.CASCADE)

    <a class="btn btn-danger" href="{% url 'delete_room' %}">Delete Room</a>*

>Solution :

You can filter on the primary key pk of the item, so:

def delete_room(request, pk):
    return redirect('home')

But you should not do this for a GET request. Removing items should be done through a POST request or a DELETE request. As the W3 organization says:

In particular, the convention has been established that the GET and HEAD methods SHOULD NOT have the significance of taking an action other than retrieval. These methods ought to be considered “safe”.

If you accept GET requests, search engines, and some browsers that already retrieve links of a page, might accidentally visit that view, and thus accidentally remove data.

You thus should limit the HTTP methods with:

from django.views.decorators.http import require_http_methods

@require_http_methods(['DELETE', 'POST'])
def delete_room(request, pk):
    return redirect('home')

For the HTML you should make a mini form like:

<form method="post" action="{% url 'delete_room' %}">
    {% csrf_token %}
    <button type="submit" class="btn btn-danger">Delete Room</button>

Leave a Reply