Deleting objects in Django

后端 未结 2 858
情书的邮戳
情书的邮戳 2020-12-07 23:08

In a mini blog app, I want to create a delete function, so that the owner of the blog can delete his entries (and only his entries). I guess that the only methods for doing

2条回答
  •  再見小時候
    2020-12-07 23:53

    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)
    

提交回复
热议问题