Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get 'value' attribute of tag <input> in Django?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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 calling reverse(…) [Django] and
then wrap it in a HttpResponseRedirect object [Django-doc].
The redirect(…) 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading