2015-08-08 184 views
0

我正在從事django電子商務項目。添加任何其他網址到我的html頁面single.html(顯示由特定的麪包師或製造商產品)給錯誤HTTP404。 所以在這個single.html頁面上顯示產品。我已添加到購物車按鈕。當我不提add_to_cart的按鈕標籤的鏈接它顯示的頁面,當我提到它給HTTP404錯誤Django error with get_absolute_url

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 

單對於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 

的.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> 

視圖urls.py

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

回答

0

這並沒有回答你的問題,但這些都在擾亂我!更嚴重的是,這些小細節加起來會讓你的工作更難。

def BakerDetail(...) =>def baker_detail(...)

def Add_To_Cart(...) =>def add_to_car(...)

try: baker = Baker.objects.get(slug=slug) ... except ... =>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 %} =>{% 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 
    }) 
+0

謝謝@Francois。有效。我會按照你所說的做出改變。 –

1

您需要將slug傳遞給url標記,以告知它要添加哪個元素。

{% url 'add_to_cart' slug=items.slug %} 

(注意,如果你調用變量「item」而不是「items」)會更清楚。