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

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

问题描述

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

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

要检查新对象是否属于某个用户,您需要在 UserNew 之间创建关联(例如 created_by = models.ForeignKey(User)New 模型中的 code>).

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

您可以通过以下方式登录用户: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天全站免登陆