创建购物车应用

时间:2015-08-09 20:03:31

标签: python django django-urls

获取错误NoReverseMatch

Reverse for 'add_to_cart' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['cart/(?P<slug>[\\w-]+)/']

urls.py

url(r'^cart/(?P<slug>[\w-]+)/', views.add_to_cart, name='add_to_cart'),

views.py

from django.core.urlresolvers import reverse
def add_to_cart(request, slug):
request.session.set_expiry(120000)

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.get(id=the_id)

try:
    product = Product.objects.get(slug=slug)
except Product.DoesNotExist:
    pass
except:
    pass

product_var = [] #product variation
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:
            pass
    cart_item = CartItem.objects.create(cart=cart, product=product)
    if len(product_var) > 0:
        cart_item.variations.add(*product_var)
    cart_item.quantity = qty
    cart_item.save()
    # success message
    return HttpResponseRedirect(reverse("cart"))
#error message
return HttpResponseRedirect(reverse("cart"))

prod.html

<form class='form' method='POST' action='{% url "add_to_cart" product.slug %}'> {% csrf_token %}
             <input class='btn btn-default btn-block' type='submit' value='Add to cart'/>
            <input  class="form-control"  name='qty' type='number' value='1'/>

            {% if product.variation_set.all %}


            {% if product.variation_set.sizes %}
            <select class='form-control' name='size'>
            {% for item in product.variation_set.sizes %}
                <option value='{{ item.title|lower }}'>{{ item.title|capfirst }}</option>
                {% endfor %}
            </select>
            {% endif %}

             {% if product.variation_set.colors %}
            <select class='form-control' name='color'>
            {% for item in product.variation_set.colors %}
                <option value='{{ item.title|lower }}'>{{ item.title|capfirst }}</option>
                {% endfor %}
            </select>
            {% endif %}



            {% endif %}

         </form>

我想我错过了一些东西。即使我提到其他网址名称,它也会显示与该网址格式相同的错误。我是否必须导入可以解决它的东西。

2 个答案:

答案 0 :(得分:0)

您尚未显示负责首先呈现prod.html的视图。但是从错误中可以清楚地看出,您作为product传递给该模板的对象的slug属性为空字符串。

答案 1 :(得分:0)

从我所看到的你没有提供的,一个必要的论点是slug,&#39; cart&#39;应该是一个字符串。 https://docs.djangoproject.com/en/1.8/ref/urlresolvers/

url = reverse('cart', args=(slug,))
return HttpResponseRedirect(url)