簡體   English   中英

模板渲染期間出錯:NoReverseMatch at /products/product-3/

[英]Error during template rendering : NoReverseMatch at /products/product-3/

你能幫我理解下面的錯誤嗎? 我正在學習 Django,並且真的堅持使用視圖的反向渲染。 當我單擊產品鏈接時,它應該轉到產品頁面,但會引發錯誤。

我的分析我在產品單個函數中插入了打印語句,並且可以在終端中看到程序運行正常,直到它呈現視圖,這有幫助嗎?

從終端

15/Nov/2020 22:49:59] "GET /products/ HTTP/1.1" 200 7582
<WSGIRequest: GET '/products/product-3/'>
{'product': <Product: Product 3>, 'images': <QuerySet []>}
products/single.html
Internal Server Error: /products/product-3/
Traceback (most recent call last):

錯誤NoReverseMatch 在 /products/product-3/ Reverse for 'add_to_cart' 未找到。 'add_to_cart' 不是有效的視圖函數或模式名稱。 請求方法:GET 請求 URL: http : //127.0.0.1 :8000/products/product-3/ Django 版本:3.1.3 異常類型:NoReverseMatch 異常值:
未找到“add_to_cart”的反向。 'add_to_cart' 不是有效的視圖函數或模式名稱。

HTML

{% extends "base.html" %} {% block content %}
<h1>Search for {{ query }}</h1>
{{ product }}

<table class="table">
  <thead>
    <th></th>
    <th>Product</th>
  </thead>
  <tbody>
    {% for product in product_htm %}
    <tr>
      <td>Image</td>
      <td><a href="{ product.get_absolute_url }}"> {{ product }}</a></td>
    </tr>
    {% endfor %}
  </tbody>
</table>
{% endblock %}

產品應用中的models.py

# Create your models here.
class Product(models.Model):
    def get_absolute_url(self):
        return reverse("product_app:single_product", kwargs={"slug": self.slug})

產品視圖.py

def single(request, slug):
    product = Product.objects.get(slug=slug)
    images = ProductImage.objects.filter(product=product)
    context = {'product': product, 'images': images}
    template = 'products/single.html'
    print(request)
    print(context)
    print(template)
    return render(request, template, context)

產品應用 urls.py來自 . 導入視圖

app_name = 'product_app'

urlpatterns = [
    path('', views.index, name='home'),
    path('s/', views.search),
    path('products/', views.all, name='products'),
    path('products/<slug:slug>/', views.single, name='single_product'),
]

購物車 urls.py

from . import views
# import (index, ProductSingleView)

app_name = 'cart_app'

extra_patterns = [
    path('cart/carts/<slug:slug>/', views.add_to_cart),
]
urlpatterns = [
    path('cart/', include(extra_patterns), name='add_to_cart'),
    path('cart/<int:id>', views.remove_from_cart, name='remove_from_cart'),
    path('', views.view, name='cart'),
]

購物車 views.py

# Create your views here.
from products.models import Product, Variation
from .models import Cart, CartItem


def view(request):
    try:
        the_id = request.session['cart_id']
    except DoesNotExist:
        the_id = None
    if the_id:
        cart = Cart.objects.get(id=the_id)
        new_total = 0.00
        for item in cart.cartitem_set.all():
            line_total = float(item.product.price) * item.quantity
            new_total += line_total

        request.session['items_total'] = cart.cartitem_set.count()
        cart.total = new_total
        cart.save()
        
        context = {"cart": cart}
    else:
        empty_message = "Yout cart is empty, please keep shopping"
        context = {"empty": True, "empty_message": empty_message}

    template = "cart/view.html"
    return render(request, template, context)

def remove_from_cart(request, id):
    try:
        the_id = request.session['cart_id']
        cart = Cart.objects.get(id=the_id)
    except:
        return HttpResponseRedirect(reverse('cart_app:cart'))

    cartitem = CartItem.objects.get(id=id)
    cartitem.cart = None
    cartitem.save()
    return HttpResponseRedirect(reverse('cart_app:cart'))

def add_to_cart(request, slug):
    request.session.set_expiry(120)

    try:
        the_id = request.session['cart_id']
    except:
        new_cart = Cart()
        new_cart.save()
        request.session['cart_id'] = new_cart.id
        the_id = new_cart.id

    cart = Cart.objects.filter(id=the_id)

    try:
        product = Product.objects.get(slug=slug)
    except Product.DoesNotExist:
        print("except1")

    product_var = []
    if request.method == "POST":
        qty = request.POST['qty']
        for item in request.POST:
            key = item
            val = request.POST[key]
            try:
                v = Variation.objects.get(product=product, category__iexact=key, title__iexact=val)
                product_var.append(v)
            except Variation.DoesNotExist:
                pass

        cart_item = CartItem.objects.create(cart=cart, product=product)
        print("iam here")
        if len(product_var) > 0:
            # * adds each item
            cart_item.variations.add(*product_var)
        cart_item.quantity = qty
        cart_item.save()


        return HttpResponseRedirect(reverse('cart_app:cart'))
    else:
        return HttpResponseRedirect(reverse('cart_app:cart'))

項目電子商務中的 urls.py

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('', include('products.urls')),
    path('cart/', include('carts.urls'), name='cart'),
    path('admin/', admin.site.urls),
]

我能看到的第一件事是你的 html 文件中有一個錯字。 你只有一個左大括號

product.get_absolute_url

此外,當您調用get_absolute_url它會返回

reverse("product_app:single_product", kwargs={"slug": self.slug})

確保產品確實有self.slug因為我無法判斷您的 models.py 中的產品類是否有任何字段。

如果這有幫助,請告訴我,我很樂意嘗試提供幫助。

在您的 url_patterns 中,包含name='add_to_cart'的行位於包含中。 把這個名字拿出來放在 extra_patterns 的那一行。 我認為您正在嘗試命名可能有多個項目的包含。

from . import views
# import (index, ProductSingleView)

app_name = 'cart_app'

extra_patterns = [
    path('cart/carts/<slug:slug>/', views.add_to_cart, name='add_to_cart'),
]
urlpatterns = [
    path('cart/', include(extra_patterns)),
    path('cart/<int:id>', views.remove_from_cart, name='remove_from_cart'),
    path('', views.view, name='cart'),
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM