Python Django delete current object

前端 未结 5 474
别那么骄傲
别那么骄傲 2020-12-10 19:26

Case I am in /notes/get/1/ where id=1 and I have created a \"Delete Note\" link in note.html. I need it to delete the current note from database and app and redirect

5条回答
  •  不知归路
    2020-12-10 19:55

    from django.shortcuts import get_object_or_404
    from django.core.urlresolvers import reverse
    
    
    def delete(request, id):
        note = get_object_or_404(Note, pk=id).delete()
        return HttpResponseRedirect(reverse('notes.views.notes'))
    

    And in urls.py

    url(r'^delete/(?P\d+)/$','project.app.views.delete'),
    

    Make sure that you check the user permissions before deleting an object, you can use the @permission_required decorator https://docs.djangoproject.com/en/1.5/topics/auth/default/#the-permission-required-decorator. If you don't check this an user can delete all notes easily.

    Usually it's a good idea to remove objects from the DB using a POST or DELETE request, instead of a GET. Imagine that google-bot crawls your site and visits notes/delete/2.

提交回复
热议问题