I am creating a ToDo list where I can create a ToDo item and provide a button against each item to update it. I am using ModelForm to save my data to DB. The update button takes me to 'update.html' with the instance of selected task. But when I update the task information and click on 'Submit', it creates a new task with the updated information and does not update the same task. Please help me, I am stuck.
views.py
from django.shortcuts import render, redirect
from .models import Task
from .forms import *
def index(request):
tasks = Task.objects.all()
form = TaskForm()
if request.method == 'POST':
form = TaskForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
context = {'tasks':tasks,'form':form}
return render(request,'TaskList/list.html',context)
def update(request, pk):
task = Task.objects.get(id = pk)
if request.method == 'POST':
form = TaskForm(request.POST, instance=task)
if form.is_valid():
form.save()
return redirect('/')
else:
form = TaskForm(instance = task)
context = {'task':task, 'form':form}
return render(request,'TaskList/update.html', context)
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name = 'list'),
path('update/<str:pk>/', views.update, name = 'update')
]
update.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form method = 'POST' action = ''>
{% csrf_token %}
{{form}}
<input type = 'submit' name = 'Update'>
</form>
</body>
</html>
list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ToDoList</title>
</head>
<body>
<form method = 'POST' action = ''>
{% csrf_token %}
{{form.title}}
<input type = 'submit' name = 'Create Task'>
</form>
{% for task in tasks %}
<div>
<a href = "{% url 'update' task.id %}">Update</a>
<p>{{task.title}}</p>
</div>
{% endfor %}
</body>
</html>
action
contains'update/<str:pk>/update'
, wich is an invalid action.print
statements, to see if you submit your form, that it is passed to the correct view?index
method will indeed create a new record. The question was, if I understood it correctly, why it is not updating, but creating a record. If you want to update the record, you need to make a POST request to theupdate
view.