Django将POST删除请求路由到viewProduct?

时间:2019-03-04 01:31:33

标签: python django

当我尝试在django应用上删除产品时,出现404错误,提示:

Page not found (404)
Request Method:     POST
Request URL:    http://localhost:8000/product/1/delete/
Raised by:  products.views.viewProduct

No Product matches the given query.

我对Django为什么将删除请求路由到viewProduct感到困惑,因为我的urls.py明确指出应该将其路由到deleteProduct。

urls.py:

from django.urls import path
from . import views
from django.views.generic import TemplateView

urlpatterns = [

    path('new/', views.NewProduct, name='NewProduct'),
    path('product/<int:pk>/<str:slug>/', views.viewProduct, name='viewProduct'),
    path('product/<int:pk>/delete/', views.deleteProduct, name='deleteProduct'),

]

观看次数:

from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponse
from .models import Product
from django.utils import timezone
from slugify import slugify


def viewProduct(request, pk, slug):
    product = get_object_or_404(Product, pk = pk, slug = slug)
    return render(request, 'viewProduct.html', {'product' : product})


def deleteProduct(request, pk):
    if request.method == 'GET':
        product = Product.objects.filter(pk = pk)   
        return redirect('viewProduct', pk = pk, slug = product.slug)
    if request.method == 'POST':
        product = get_object_or_404(Product, pk = pk)
        if product.productAuthor == request.user:
            product.delete()
    return redirect('viewAll')

删除表格:

{% if request.user == product.productAuthor %}
    <form action="/product/{{ product.pk }}/delete/" method="post">
        {% csrf_token %}
        <input type="submit" name="pk" class="btn btn-link text-danger" value="delete product">
    </form>
{% endif %}

如果有帮助,我最近更改了网站,以按ID和slug(而不只是ID)查看帖子。在我更改此设置之前,删除功能运行良好。

2 个答案:

答案 0 :(得分:0)

也许这是删除后缩进的方式,请尝试

我看不到要重定向的viewAll URL处理程序,需要编写一个viewAll视图,列出所有产品

from django.urls import reverse


urlpatterns = [
    path('',views.ViewAll, name='viewAll')
    path('new/', views.NewProduct, name='NewProduct'),
    path('product/<int:pk>/<str:slug>/', views.viewProduct, name='viewProduct'),
    path('product/<int:pk>/delete/', views.deleteProduct, name='deleteProduct'),

]


def deleteProduct(request, pk):
    if request.method == 'GET':
        product = Product.objects.filter(pk = pk)   
        return redirect('viewProduct', pk = pk, slug = product.slug)
    if request.method == 'POST':
        product = get_object_or_404(Product, pk = pk)
        if product.productAuthor == request.user:
            product.delete()
            return redirect(reverse('yourappname:viewAll'))

答案 1 :(得分:0)

URL模式按顺序处理。 “删除”是一个is的完全有效的值,因此视图模式被匹配并调用其视图。

您可以通过交换URL的顺序来解决此问题,以便首先匹配“删除”。