I have this view function to delete task from ToDo application:
def delete_task(request):
if request.method == 'POST':
task = Task.objects.get(pk=request.POST['delete'])
task.delete()
return HttpResponseRedirect(reverse('todoapp:index'))
else:
tasks = Task.objects.all()
return render(request, 'index.html', {'tasks': tasks})
I get ‘value’ of tag
Here is my html:
<form action="{% url 'todoapp:delete_task' %}" method="post">
{% csrf_token %}
<input type="submit" name="delete" value="{{ task.id }}" class="btn btn-primary">
</form>
And my button shows id of task instead of word ‘Delete’ any ideas how I can get data of tag <input> in another way?
Thank you advance!!
>Solution :
Well the value="…" [mdn-doc] in an <input type="button"> is used to show the text in the button.
An equivalent way to do this would be to use a <button> where you have more freedom to specify the content of the button, so:
<form action="{% url 'todoapp:delete_task' %}" method="post">
{% csrf_token %}
<button type="submit" name="delete" value="{{ task.id }}" class="btn btn-primary">Delete</button>
</form>
That being said, typically the primary key is encoded in the URL, this ensures that Django will only route the request to your view if such primary key is present.
Your view can also be improved to:
from django.shortcut import redirect
def delete_task(request):
if request.method == 'POST':
task = Task.objects.filter(pk=request.POST['delete']).delete()
return redirect('todoapp:index')
else:
tasks = Task.objects.all()
return render(request, 'index.html', {'tasks': tasks})
Note: You can make use of
redirect(…)[Django-doc] instead
of first callingreverse(…)[Django] and
then wrap it in aHttpResponseRedirectobject [Django-doc].
Theredirect(…)function does not only offer a more convenient signature to do this, it also for example will use the
.get_absolute_url()method [Django-doc]
if you pass it a model object.