0

My update view isnt working when i submit the update form it dosent update the form. When i click the update button it just shows me the original post (unedited). if anyone could help that would be great.

views.py

from django.shortcuts import render
from django.shortcuts import HttpResponseRedirect
from .models import Post
from .forms import PostForm


def post_list(request):
    posts = Post.objects.all()
    context = {
        'post_list': posts
    }
    return render(request, "posts/post_list.html", context)


def post_detail(request, post_id):
    post = Post.objects.get(id=post_id)
    context = {
        'post': post
    }
    return render(request, "posts/post_detail.html", context)


def post_create(request):
    form = PostForm(request.POST or None)
    if form.is_valid():
        form.save()
        return HttpResponseRedirect('/posts')
    context = {
        "form": form,
        "form_type": 'Create'
    }
    return render(request, "posts/post_create.html", context)


def post_update(request, post_id):
    post = Post.objects.get(id=post_id)
    form = PostForm(request.POST or None, instance=post)
    if form.is_valid():
        form.save()
        return HttpResponseRedirect('/posts')
    context = {
        "form": form,
        "form_type": 'Update'
    }
    return render(request, "posts/post_create.html", context)

urls.py

from django.urls import path
from .views import post_list, post_detail, post_create, post_update


urlpatterns = [
    path('', post_list),
    path('create/', post_create),
    path('<post_id>/', post_detail),
    path('<post_id>/update', post_update),
]
Naveed naseer
  • 85
  • 1
  • 10
  • you can't render two views to a single html template , go check [render two views to a single html template](https://stackoverflow.com/questions/42132010/render-two-views-to-a-single-html-template) – Ninou Jul 06 '20 at 12:19
  • i am following a youtube tutorial and it worked fine for him – Naveed naseer Jul 06 '20 at 12:23
  • yes you can render two views to a single template. This is where DRY principle takes place. – ngawang13 Jul 07 '20 at 05:52
  • in your return HttpResponseRedirect('/posts') where have you specify the posts url. Check if its updating in you database. – ngawang13 Jul 07 '20 at 05:54

0 Answers0