This is how my ToDoapp looks like
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 >
{% for task in tasklist %}
<li >
<input type='hidden' name = 'task_id' value='{{task.id}}'>{{task.tasks}}
<span >{{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.
CodePudding user response:
Each row shall be in an independent form as currently the form has 3 elements with the same name
CodePudding user response:
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
CodePudding user response:
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 >
{% for task in tasklist %}
<li >
<form method="POST">
{%csrf_token%}
<input type='hidden' name = 'task_id' value='{{task.id}}'>{{task.tasks}}
<span >{{task.duedate}}
<input type="date" name="datepick" />
<input type='submit' value ='Update'>
</span>
</form>
</li>
{% endfor %}
</ul>