【发布时间】:2015-08-08 21:08:41
【问题描述】:
我正在从事 django 电子商务项目。将任何其他 url 添加到我的 html 页面 single.html(显示特定面包师或制造商的产品)会产生错误 HTTP404。 所以在这个single.html 页面上显示产品。我添加了添加到购物车按钮。当我没有在按钮标签中提到 add_to_cart 的链接时,它会显示页面,当我提到它时会给出 HTTP404 错误
views.py 用于显示制造商(在我的例子中是面包师)
def BakerDetail(request, slug):
try:
baker = Baker.objects.get(slug=slug)
products = Product.objects.filter(baker=baker)
context = {
'baker': baker,
'products': products
}
template = 'bakers/single.html'
return render(request, template, context)
except:
raise Http404
single.html
<table class='table'>
<thead>
<th></th>
<th>Products</th>
</thead>
<tbody>
{% for items in products %}
<tr>
<td></td>
<td>
<a href="{{ items }}">
{{ items }}</a>
{{ items.price }}
<button class="btn btn-primary" href="{% url 'add_to_cart' %}">Add To Cart</button>
</td>
<td></td>
</tr>
{% endfor %}
</tbody>
</table>
查看 add_to_cart
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
urls.py
url(r'^cart/(?P<slug>[\w-]+)/$', views.Add_To_Cart, name='add_to_cart'),
【问题讨论】:
标签: python django django-models django-views django-urls