尝试连接到URL时出现Django NoReverseMatch错误

时间:2019-10-13 15:39:27

标签: python django

当我尝试连接到我的URL时出现NoReverseMatch错误,并且我不确定是什么问题。感谢您的任何帮助。这是我的代码:

cart / models.py

from shop.models import Product

class Cart(models.Model):
    cart_id = models.CharField(max_length=250, blank = True)
    date_added = models.DateField(auto_now_add = True)
    class Meta:
        db_table = 'Cart'
        ordering = ['date_added']

    def __str__(self):
        return self.cart_id

class CartItem(models.Model):
    product = models.ForeignKey(Product, on_delete = models.CASCADE)
    cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
    quantity = models.IntegerField()
    class Meta:
        db_table = 'CartItem'

    def sub_total(self):
        return self.product.price * self.quantity

    def __str__(self):
        return self.product

购物车/views.py

错误似乎源于此处的add_cart方法,表示该操作没有反向。

from shop.models import Product
from .models import Cart, CartItem
from django.contrib import messages
from django.core.exceptions import ObjectDoesNotExist

def _cart_id(request):
    cart = request.session.session_key
    if not cart:
        cart = request.session.create()
    return cart


def add_cart(request, product_id):
    product = Product.objects.get(id=product_id)
    try:
        cart = Cart.objects.get(cart_id=_cart_id(request))
    except Cart.DoesNotExist:
        cart = Cart.objects.create(
                cart_id = _cart_id(request)
            )
        cart.save()
    try:
        cart_item = CartItem.objects.get(product=product, cart=cart)
        if cart_item.quantity < cart_item.product.stock:
            cart_item.quantity += 1
            cart_item.save()
        else:
            messages.add_message(request, messages.INFO,
                    'Sorry, no more available!')
    except CartItem.DoesNotExist:
        cart_item = CartItem.objects.create(
            product = product,
            quantity = 1,
            cart = cart
        )
        cart_item.save()
    return redirect('cart_detail')

def cart_detail(request, total=0, counter=0, cart_items=0):
    try:
        cart = Cart,objects.get(cart_id=_cart_id(request))
        cart_items = CartItem.objects.filter(cart=cart)
        for cart_item in cart_items:
            total += (cart_item.product_price * cart_item.quantity)
            counter += cart_item.quantity
    except ObjectDoesNotExist:
        pass
    return render(request, 'cart.html', dict(cart_items = cart_items, total = total, counter = counter))

购物车/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('add/<int:product_id>/', views.add_cart, name='add_cart'),
    path('', views.cart_detail, name='cart_detail'),
]

urls.py

from django.contrib import admin
from django.urls import path, include

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

错误 enter image description here

1 个答案:

答案 0 :(得分:1)

当您尝试反向URL而不为URL提供必需的参数时,将导致此问题。有两种情况可能导致此问题:

  1. 您可以使用add_cartfrom django.urls import reverse视图保留网址(看看您的商店视图):
    # ERROR. It will cause if you're not put any input data on it as your urls defined - missing product_id
    url = reverse('app_name:add_cart')

    # PASS
    url = reverse('app_name:add_cart', kwargs={'product_id': 4})
  1. shop视图的模板上,如果您使用url标签:

如果您未将product_id放入url标记中,也会导致此问题。

<form method="POST" action="{% url 'app_name:add_cart' %}">

</form>

所以它应该是:

<form method="POST" action="{% url 'app_name:add_cart' product_id=your_product_id %}">

</form>

希望这为您提供了足够的信息来解决问题