在Django中删除对象 [英] Deleting objects in Django

查看:101
本文介绍了在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:

如果您的网址指向了像您这样的网址:< 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 New 之间创建实现(例如 created_by = models.ForeignKey(User) (在 New 模型中)。

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天全站免登陆