Reputation: 5
I am trying to delete an object. This is the HTML, todo
should be deleted when you Click on button (I am trying to call delete_todo
) :-
<ul>
{% for all %}
</ul>
This is the views.py,
Upvotes: 0
Views: 1289
Reputation: 1
Just to add clarification on the use of the form and csrf: it's necessary in order to ensure that different users of your app can't delete content that isn't theirs.
In your template, you'll need to include the csrf tag as such:
<form method="post" action={% url 'delete_todo' todo_id=todo.id %}>
{% csrf_token %}
<input type="button" id="submit" value="Delete" />
</form>
Upvotes: 0
Reputation: 47354
You need to change few things in your code.
First of all change urlpattern delete_todo
you need to add argument, which allows to determine in view what object you want to delete:
url(r'^(?P<todo_id>[0-9]+)/$', views.delete_todo, name='delete_todo'),
Then you need change delete_todo
itself:
def delete_todo(request, todo_id):
instance = get_object_or_404(Todo, pk=todo_id)
instance.delete()
return redirect('index')
Here you can use get_object_or_404
fuction to get object with id.
And finally you need to pass url's argument to view from template:
<form action="{% url 'lists:delete_todo' todo_id=todo.id %}" method=post>
<input id="submit" type="button" value="Click" />
</form>
Upvotes: 1