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))
and in the template:
<a href='/news/delete_new/{{object.id}}/'> Delete</a> <br />
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)
In general, for deleting objects you should rather use POST (or DELETE) HTTP methods.
If you really want to use HTTP GET for your example, here is what you need to fix:
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:To check if New objects belogs to some user you need to create realation between
UserandNew(likecreated_by = models.ForeignKey(User)inNewmodel).You can get logged in user this way:
request.userI 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.