【问题标题】:form.save() not working my form.save for updating data isnt workingform.save() 不起作用我的 form.save 用于更新数据不起作用
【发布时间】:2020-10-26 19:50:15
【问题描述】:

form.save() 不起作用我的 form.save 用于更新数据当我尝试更新我的帖子时它显示原始未编辑的帖子它不保存更新的版本。我不知道是什么导致错误 idk 如果它的意见或模板中的任何内容,如果有人可以提供帮助,我将非常感激,请提供帮助。

代码如下:

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>

【问题讨论】:

  • 更新帖子是否会将您重定向到 /posts?
  • 不,它需要我去 /posts/1
  • 请不要就同一个问题提出多个问题。当您的所有信息都分布在多个页面上时,这使得提供帮助变得更加困难。如果您有更多信息要补充,您可以edit您的原始问题。
  • 很抱歉,我会记住这一点

标签: python django django-forms django-views django-templates


【解决方案1】:

action="." 将您从&lt;post_id&gt;/update 带到&lt;post_id&gt;/。您可以通过以下几种方式解决此问题:

  1. 将其更改为action="",它将从&lt;post_id&gt;/update提交到&lt;post_id&gt;/update
  2. 在 URL 中添加一个斜杠,即path('&lt;post_id&gt;/update/', ...)。然后action="." 将从&lt;post_id&gt;/update/ 提交到&lt;post_id&gt;/update/
  3. 使用{% url %} 标记而不是硬编码操作。在你的情况下,你需要做一些改变,所以我会把它作为一个挑战留给你。 reversing URLs 上的文档应该会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多