使用DeleteView不允许使用方法(POST)

时间:2017-11-06 18:35:54

标签: python django

我是Django的新手,我使用基于类的视图向我的餐厅列表添加删除选项,但是当我点击删除按钮时,我得到一个空白屏幕并在控制台中收到以下错误 “不允许的方法(POST):”

以下是我的代码

views.py

from __future__ import unicode_literals
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView, ListView, DetailView, 
CreateView,DeleteView
from django.urls import reverse_lazy

class RestaurantDeleteView(DeleteView):
model = RestaurantLocation
success_url = reverse_lazy('restaurants:list')

urls.py

from django.conf.urls import url, include

from .views import (

     RestaurantListView,
     RestaurantDetailView,
     RestaurantCreateView,
     RestaurantDeleteView,
   )

urlpatterns = [
    url(r'^create/$', RestaurantCreateView.as_view(), name= 'create'),
    url(r'^$',RestaurantListView.as_view(), name= 'list'),
    url(r'^(?P<slug>[\w-]+)/$',RestaurantDetailView.as_view(),        
          name="detail"),
    url(r'^(?P<slug>[\w-]+)/delete/$', RestaurantDeleteView.as_view(), 
     name="restaurant-delete"),
   ]

delete.html

<form method="post" action="" >{% csrf_token %}
<p>Are you sure you want to delete <strong> {{ obj }}</strong>?</p>
<input type="submit" value="DELETE" />
</form>

2 个答案:

答案 0 :(得分:0)

你的delete.html中的

方法目前是&#34; t&#34;,更改为&#34; post&#34;看看是否有效。

答案 1 :(得分:0)

您的表单操作指向/的根网址。 此路线由RestaurantListViews确定,并通过GET方法加入。 在您的示例中,您尝试使用POST访问此内容,因此您收到错误。

要使用RestaurantDeleteView更改表单中的action属性,请指向现有的餐馆,例如:

<form method="post" action="{your_existing_restaurant_slug}/delete" >
    {% csrf_token %}
    ...
...