django删除对象 [英] django delete object

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

问题描述

在迷你博客应用程序中,我想创建一个删除功能,以便博客的所有者可以删除他的条目(只有他的条目)。
我猜想做唯一的做法是使用一个表单。
虽然我的删除代码看起来很清楚和正确,但它不起作用。
我的代码:

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 do, is using a form. Though my the deletion code seems clear and correct, it doesn't work. My code:

def delete_new(request,id):
   u = New.objects.get(pk=id).delete()
   if request.method == 'POST':
       form = DeleteNewForm(request.POST)    
       form.u.delete()             
       form.save()   
   return render_to_response('news/deleteNew.html', {
           'form': form,
           }, 
        context_instance=RequestContext(request)) 

在模板中:

<a href='/news/delete_new/{{object.id}}/'> Delete</a> <br /> 

这是否正确?我的意思是,为此创建一个表单?
也是,与删除链接相关联的博客文章的唯一方法是将id作为参数。这样对吗?我的意思是,也许任何用户都可以在url中输入另一个id,并删除另一个条目(最终不是他的一个)。

Is this a correct approach? I mean, creating a form for this? also, the only way to take the blog post associated with the deletion link is having an id as a parameter. Is it right? I mean, maybe any user can type another id, in the url, and delete another entry (eventually not one of his)

推荐答案

一般来说,删除对象时,您应该使用POST(或DELETE) HTTP方法

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

如果您真的想使用HTTP GET作为示例,那么您需要修复以下内容:

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

如果你有url指向像你这样的URL:< a href ='/ news / delete_new / {{object.id}} /'>删除< / a> 然后您可以简单地写入视图,检查对象是否属于登录用户,如果是,则删除此条目,如您已经编写的代码:

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

要检查新对象是否为某些用户需要在 User 之间创建实现(如 created_by = models.ForeignKey(User) 新建模型)

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

您可以通过以下方式登录用户: code> request.user

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

我希望我能正确点,我的答案可以帮助你。

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

PS:您也可以考虑使用 {%url%} 标签,而不是直接在模板中编写URL。

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

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

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