[Django]-Deleting objects in Django

21👍

In general, for deleting objects you should rather use POST (or DELETE) HTTP methods.

If you really want to use HTTP GET for your example, here is what you need to fix:

If you have url pointing to some url like yours: <a href='/news/delete_new/{{object.id}}/'> Delete</a> then you can simply write view that will check if object belongs to logged in user and delete this entry if yes, like in code you have already written:

def delete_new(request,id):
   #+some code to check if New belongs to logged in user
   u = New.objects.get(pk=id).delete()

To check if New objects belogs to some user you need to create realation between User and New (like created_by = models.ForeignKey(User) in New model).

You can get logged in user this way: request.user

I hope I got your point correctly and my answer helps you somehow.

PS: You can also consider using {% url %} tag instead of writing urls directly in your templates.

👤dzida

35👍

You need to use a form, or you’re vulnerable to CSRF attacks. You’re also deleting the model before you’ve checked whether the request was a GET or a POST.

Create a simple ModelForm:

from django import forms

from .models import New

class DeleteNewForm(forms.ModelForm):
    class Meta:
        model = New
        fields = []

In your views.py in the same Django app:

from django.shortcuts import render, get_object_or_404

from .forms import DeleteNewForm
from .models import New

def delete_new(request, new_id):
    new_to_delete = get_object_or_404(New, id=new_id)
    #+some code to check if this object belongs to the logged in user

    if request.method == 'POST':
        form = DeleteNewForm(request.POST, instance=new_to_delete)

        if form.is_valid(): # checks CSRF
            new_to_delete.delete()
            return HttpResponseRedirect("/") # wherever to go after deleting

    else:
        form = DeleteNewForm(instance=new_to_delete)

    template_vars = {'form': form}
    return render(request, 'news/deleteNew.html', template_vars)

Leave a comment