form.save() 不工作我的 form.save 更新數(shù)據(jù)不工作當(dāng)我嘗試更新我的帖子它顯示原始未經(jīng)編輯的帖子它發(fā)送保存更新的版本。我不知道是什么導(dǎo)致錯(cuò)誤 idk 如果它的視圖或任何在模板如果有人可以提供幫助,我將不勝感激,請(qǐng)?zhí)峁椭?。這是代碼:views.pyfrom django.shortcuts import renderfrom django.shortcuts import HttpResponseRedirectfrom .models import Postfrom .forms import PostFormdef 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.pyfrom django.urls import pathfrom .views import post_list, post_detail, post_create, post_update, post_deleteurlpatterns = [ 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 回答

暮色呼如
TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超9個(gè)贊
action="."
帶你從<post_id>/update
到<post_id>/
。您可以通過幾種方式解決此問題:
將其更改為
action=""
,這將從提交<post_id>/update
到<post_id>/update
。在 URL 中添加斜杠,即
path('<post_id>/update/', ...)
. 然后action="."
將從提交<post_id>/update/
到<post_id>/update/
使用
{% url %}
標(biāo)簽而不是對(duì)操作進(jìn)行硬編碼。在你的情況下,你需要做一些改變,所以我將把它作為一個(gè)挑戰(zhàn)留給你。有關(guān)反轉(zhuǎn) URL 的文檔應(yīng)該有所幫助。
添加回答
舉報(bào)
0/150
提交
取消