问题
form.save() not working my form.save for updating data isnt working when i try to update my post it shows the original unedited post it dosent save the updated version.i donnt know whats causing the error idk if its views or anything in template if anyone could help i will be very grateful please help.
here is the code:
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_update.html", context)
def post_delete(request, post_id):
post = Post.objects.get(id=post_id)
post.delete()
return HttpResponseRedirect('/posts')
urls.py
from django.urls import path
from .views import post_list, post_detail, post_create, post_update, post_delete
urlpatterns = [
path('', post_list),
path('create/', post_create),
path('<post_id>/', post_detail),
path('<post_id>/update', post_update),
path('<post_id>/delete', post_delete),
]
post_update.html
<h1>welcome to post {{ form_type }}</h1>
<form method="POST" action=".">
{% csrf_token %}
<p>{{ form.as_p }}</p>
<button type="submit">{{ form_type }}</button>
</form>
回答1:
action="."
takes you from <post_id>/update
to <post_id>/
. You can fix this a few ways:
- Change it to
action=""
, which will submit from<post_id>/update
to<post_id>/update
. - Add a slash to the URL, i.e.
path('<post_id>/update/', ...)
. Thenaction="."
will submit from<post_id>/update/
to<post_id>/update/
- Use the
{% url %}
tag instead of hardcoding the action. In your case there's a few changes you'd need to make, so I'll leave that as a challenge for you. The docs on reversing URLs should help.
来源:https://stackoverflow.com/questions/62760276/form-save-not-working-my-form-save-for-updating-data-isnt-working