TOday I am trying to make some kind of to-do list. I know how to add tasks(comments) and now I want to delete them with a button. I don't know how to delete exact task (comment). Code:
#views.py
def add_comment(request):
comments = Comment.objects.all()
if request.method == 'POST':
form = CommentForm(request.POST)
if "delete" in request.POST:
#HERE MAGIC HAPPENS
if form.is_valid():
save_it = form.save()
return render(request, 'task-result.html', {
'form': form, 'comments': comments,
})
else:
form = CommentForm()
return render(request, 'Task-form.html', {
'form': form,
})
#HTML
<form action="">
{% for a in comments %}
<h3>{{ a.body}}</h3>
<input type="submit" name="delete" value="delete" />
{% endfor %}
{% csrf_token %}
</form>
So how to make "magic" happen?
Addition
Now I'm facing new problems. Delete button does nothing or i get eroor: invalid literal for int() with base 10: ''. Code:
#Template:
<html>
<head>
<title>Name</title>
</head>
<body>
<h1>Tasks</h1>
<form action="" method="post">
{{ form.as_p }}
<input type="submit" value="Create task">
{% for a in comments %}
<h3>{{ a.body}}</h3>
<input type="submit" name="delete" value="delete" />
<input type="hidden" name="idcomment" id="{{comments.id}}" />
{% csrf_token %}
</form>
{% endfor %}
</body>
</html>
#Views
def add_comment(request):
comments = Comment.objects.all()
if request.method == 'POST':
form = CommentForm(request.POST)
if "delete" in request.POST:
comments_id = request.POST['idcomment']
comments_object = Comment.objects.get(id=comments_id)
comments_object.delete()
if form.is_valid():
save_it = form.save()
return render(request, 'task-form.html', {
'form': form, 'comments': comments,
})
else:
form = CommentForm()
return render(request, 'Task-form.html', {
'form': form, 'comments': comments,
})
Can you help me solve this one?