Django – Updating value only for the last item of list

Question:

This is how my ToDoapp looks like

To Do App

The date change works only for the last item in the list but for other items it throws the error:

ValidationError at /
['“” value has an invalid date format. It must be in YYYY-MM-DD format.']

I see that irrespective of "Update" button I press, it passes only the last item’s id and date.

Find my code below:

Index.html

{% extends 'base.html' %}
{% block content %}

<h3 style = "margin-bottom: 20px"><strong>To Do List App</strong></h3>

<form method="POST">
    {%csrf_token%}
<ul class="list-group">

{% for task in tasklist %}
<li class="list-group-item d-flex justify-content-between align-items-center">
    <input type='hidden' name = 'task_id' value='{{task.id}}'>{{task.tasks}}
    <span class="badge bg-primary rounded-pill">{{task.duedate}}
        <input type="date" name="datepick" />
        <input type='submit' value ='Update'>   
    </span>
</li>
{% endfor %}

</form>

Views.py

def index(request):
    if request.method == "POST":
        task_id = request.POST.get('task_id')
        task=Task.objects.get(id=task_id)
        datepick = request.POST.get('datepick')
        task.duedate = datepick
        task.save()
    tasklist = Task.objects.all()
    return render(request, 'index.html', {'tasklist':tasklist})

Models.py

class Task(models.Model):
    tasks = models.CharField(max_length=200)
    duedate = models.DateField(blank=True)

I feel that mistake is in the HTML file and I’m not familiar with HTML.

Asked By: Saassy

||

Answers:

Each row shall be in an independent form as currently the form has 3 elements with the same name

Answered By: Mohamed ElKalioby

You should provide a unique name for each element in a form. As it is inside an iterator you can use {{ forloop.counter }} as name.

The link below would be helpful:

Django – iterate number in for loop of a template

Answered By: Salmanul faris M P

Each task on the list should have its own form.

{% extends 'base.html' %}
{% block content %}
<h3 style = "margin-bottom: 20px"><strong>To Do List App</strong></h3>
<ul class="list-group">
{% for task in tasklist %}
<li class="list-group-item d-flex justify-content-between align-items-center">
<form method="POST">
    {%csrf_token%}
    <input type='hidden' name = 'task_id' value='{{task.id}}'>{{task.tasks}}
    <span class="badge bg-primary rounded-pill">{{task.duedate}}
    <input type="date" name="datepick" />
    <input type='submit' value ='Update'>  
    </span>
</form>
    </li>
{% endfor %}
</ul>