views:

34

answers:

1

Hello, 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 methos 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)) 

and in the template:

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

Is this a correct appropach? 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) Thanks so much!

+1  A: 

You don't need form for this I think.

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

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

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

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

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

Lukasz Dziedzia
i'll check! seems logical, anyway! Thx!
dana
it rolls smoothly, and in just one line: u = New.objects.filter(created_by = request.user).get(pk=id).delete()thank you! :)
dana
Exactly, you can add some error handling if there is no such New object for a given user and display nice error message (with your one liner it will fails loudly with 500 error). But basically that is all what you need to do here:) I'm glad that my answer was helpful for you.
Lukasz Dziedzia
I'd strongly recommend using a form and checking POST, because GETs to pages are not supposed to change the state on the server. (Although, in practice what's happening here is relatively 'safe')
stevejalim