Python Django删除当前对象 [英] Python Django delete current object

查看:306
本文介绍了Python Django删除当前对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

案例我在/ notes / get / 1 / where id = 1,我在notes.html中创建了一个删除注释链接。我需要它从数据库和应用程序中删除当前的注释,并重定向到/ notes / all。你可以用def中的代码来帮我吗?

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 to /notes/all. Can you help me with the code in def delete?

models.py:

models.py:

class Note(models.Model): 
   title = models.CharField(max_length=200)
   body = models.TextField()
   cr_date = models.DateTimeField(auto_now_add=True)

urls.py:

urlpatterns = patterns('',

  url(r'^all/$', 'note.views.notes'), 
  url(r'^get/(?P<note_id>\d+)/$', 'note.views.note'), #
  url(r'^language/(?P<language>[a-z\-]+)/$', 'note.views.language'), # 
  url(r'^create/$', 'note.views.create'),
  url(r'^delete/$', 'note.views.delete'), <--------------------------
  url(r'^search/$', 'note.views.search_titles'),
 )

views.py:

def delete(??????):
    ?????  <-------------------------------------------
    return HttpResponseRedirect('/notes/all')


推荐答案

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'))

urls.py

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

确保在删除对象之前检查用户权限,可以使用@permission_required装饰器 https://docs.djangoproject.com/en/1.5/topics/auth/default/#the-permission-required-装饰机。如果您不检查这一点,用户可以轻松地删除所有注释。

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.

通常,使用POST或DELETE请求从数据库中删除对象是一个好主意,而不是一个GET。想象一下,google-bot会抓取您的网站并访问笔记/ delete / 2。

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.

这篇关于Python Django删除当前对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆