-1

My updateView creates a new post instead of updating the old post. i want to update my post but when i go to update form it creates a totally new post

views.py

def edit_task(request, post_id):
    post = Post.objects.get(id=post_id)
    form = TaskForm(instance=post)
    if request.method == 'POST':
        print(request.POST)
        form = TaskForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('task')
    context = {'form': form}
    return render(request, 'List/add_task.html', context)
Naveed naseer
  • 85
  • 1
  • 10

1 Answers1

0

You need to pass the instance for GET requests and POST requests:

if request.method == 'POST':
    form = TaskForm(request.POST, instance=post)
Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • It's the code in `if request.method == 'POST'` that you need to change. – Alasdair Jul 10 '20 at 11:29
  • thanks alot it worked but when i edit the post it shows empty form why it dosent show the old post data – Naveed naseer Jul 10 '20 at 12:08
  • That's a separate problem, that I've answered on your [other question](https://stackoverflow.com/questions/62834707/how-can-i-prepopulate-this-update-form). It sounds like you changed the wrong line (when you said *I added request.POST*), and then never changed it back to `form = TaskForm(instance=post)`. – Alasdair Jul 10 '20 at 16:56