0

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.

Saassy
  • 63
  • 7
  • Can you print datepick in your code and check what is the format of date you are getting. also share your models.py – Deepak Tripathi Oct 11 '22 at 08:53
  • @DeepakTripathi Added the models.py. The print/datepick function works correctly for the last item( 'Do Cycling' ) or whatever is in the last item. The function only passes the id of the last item regardless of whichever 'Update' button I press. – Saassy Oct 11 '22 at 09:19

3 Answers3

1

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

Mohamed ElKalioby
  • 1,908
  • 1
  • 12
  • 13
1

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

Oleg Barabanov
  • 2,468
  • 2
  • 8
  • 17
1

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>