微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

不允许 Django UpdateView 方法POST

如何解决不允许 Django UpdateView 方法POST

当我在更新页面 (http://127.0.0.1:8000/account/15/update) 上点击“保存”时,我得到

[19/Mar/2021 13:47:18] "GET /account/15/update HTTP/1.1" 200 2311
Method Not Allowed (POST): /account/15/
Method Not Allowed: /account/15/
[19/Mar/2021 13:47:24] "POST /account/15/ HTTP/1.1" 405 0

数据库记录没有得到更新,所以看起来有些东西地失败了。查看错误消息,我们似乎最终在“帐户详细信息”页面而不是“帐户更新”页面上尝试 POST - 这是怎么发生的?

这是我的 Accounts\urls.py

from django.urls import path
from .views import (
AccountCreateView,AccountListView,AccountDetailView,AccountUpdateView,AccountDeleteView
)

app_name = 'account'
urlpatterns = [
path('',AccountListView.as_view(),name='account-list'),path('create/',AccountCreateView.as_view(),name='account-create'),path('<int:pk>/',AccountDetailView.as_view(),name='account-detail'),path('<int:pk>/update',AccountUpdateView.as_view(),name='account-update'),path('<int:pk>/delete',AccountDeleteView.as_view(),name='account-delete'),]

这是我的 Accounts\views.py

from django.shortcuts import render,get_object_or_404,redirect

from django.views.generic import (
    CreateView,DetailView,ListView,UpdateView,DeleteView
)

from .forms import AccountForm
from .models import Account

class AccountCreateView(CreateView):
    form_class = AccountForm
    template_name = 'Accounts/account_create.html'
    queryset = Account.objects.all().order_by("-pk")

    def form_valid (self,form):
        return super().form_valid(form)

class AccountDetailView(DetailView):

    def get_object(self):
        account_id = self.kwargs.get("pk")
        return get_object_or_404(Account,account_id=account_id)

class AccountUpdateView(UpdateView):
    form_class = AccountForm
    template_name = 'Accounts/account_create.html'

    def get_object(self):
        account_id = self.kwargs.get("pk")
        return get_object_or_404(Account,account_id=account_id)

    def form_valid (self,form):
        return super().form_valid(form)

这是我的 Accounts\account_create.html(我用它来创建和更新)

{% extends 'base.html' %}
{% block content %}
    <h1>Account Create/Update Page for {{ request.user }} </h1>
    This is the InApp Account Create/Update Page<p/>
    <form action="." method='POST' enctype="multipart/form-data"> {% csrf_token %}
        <table id="accountdetail">
            {{ form.as_table }}
        </table>
        <p/>
        <input type="submit" value="Save"/> &nbsp;&nbsp;
        <button onclick="location.href='/account'" type="button">Cancel</button>
    </form>
{% endblock %}

我错过了什么?谢谢。

解决方法

您在 HTML 中的表单明确地将 POST 数据发送到“.”:

var selected = $('#'+label_id).find('option:selected').text();

所以我相信 <form action="." method='POST' enctype="multipart/form-data"> 变成了 /account/15/update,就像向上移动一个目录一样。如果您真的想使用相同的模板,您可以尝试以下操作:

/account/15

另外,请注意 enctype 属性只能与 method="POST" 一起使用

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。