我正在开发django电子商务项目。将任何其他网址添加到我的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'),
答案 0 :(得分:1)
您需要将slug传递到url
标记,告诉它要添加哪个元素。
{% url 'add_to_cart' slug=items.slug %}
(注意如果你调用变量&#34; item&#34;,而不是&#34; items&#34;)会更清楚。
答案 1 :(得分:0)
这不是回答你的问题,但这些都在困扰我!更严重的是,这些小细节加起来会让你的工作更加努力。
def BakerDetail(...)
=&gt; def baker_detail(...)
def Add_To_Cart(...)
=&gt; def add_to_car(...)
try: baker = Baker.objects.get(slug=slug) ... except ...
=&gt; baker = get_object_or_404(Baker, slug=slug)
见:https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#get-object-or-404
{% for items in products %}
=&gt; {% for item in products %}
为了清楚你的观点看起来像这样(行为是一样的):
def baker_detail(request, slug):
baker = get_object_or_404(Baker, slug=slug)
products = Product.objects.filter(baker=baker)
return render(request, 'bakers/single.html', {
'baker': baker,
'products': products
})