2017-02-10 1 views
0

Ich möchte Einkaufswagen in meinem django-shop erstellen.i neue App mit dem Namen Warenkorb starten und neue Datei zu dieser App hinzufügen cart.py. In dieser Datei habe ich class Cart erstellt und eine Funktion hinzugefügt. Dies ist cart.pyDjango cart_add card.py Keine Artikel anzeigen

class Cart(object): 
    def __init__(self, request): 
     """ 

     Inicjaliazacja koszyka na zakupy. 
     """ 
     self.session = request.session 
     cart = self.session.get(settings.CART_SESSION_ID) 
     if not cart: 
      # pusty koszyk w sesji 
      cart = self.session[settings.CART_SESSION_ID] = {} 
     self.cart = cart 

    def add(self, product, quantity=1, update_quantity=False, size=None, upd_size=False): 
     """ 
     Dodanie produktu i zmiana ilości 
     """ 
     product_id = str(product.id) 
     if product_id not in self.cart: 
      self.cart[product_id] = {'quantity': 0, 
            'size': None, 
            'price': str(product.price)} 
     if update_quantity: 
      self.cart[product_id]['quantity'] = quantity 
     else: 
      self.cart[product_id]['quantity'] += quantity 
     if upd_size: 
      self.cart[product_id]['size'] = size 
     else: 
      self.cart[product_id]['size'] += size 
     self.save() 

    def save(self): 
     self.session[settings.CART_SESSION_ID] = self.cart 
     self.session.modified = True 

    def remove(self, product): 
     """ 
     Usunięcie produktów z koszyka 
     """ 
     product_id = str(product.id) 
     if product_id in self.cart: 
      del self.cart[product_id] 
      self.save() 

    def __iter__(self): 
     """ 
     Iteracja przez elementy na zakupy i pobranie z bazy danych 
     """ 

     product_ids = self.cart.keys() 
     products = Product.objects.filter(id__in=product_ids) 
     for product in products: 
      self.cart[str(product.id)]['product'] = product 

     for item in self.cart.values(): 
      item['price'] = Decimal(item['price']) 
      item['total_price'] = item['price'] * item['quantity'] 
      yield item 

    def __len__(self): 
     """ 
     Obliczanie liczby wszytskich elementów w koszyku. 
     """ 
     return sum(item['quantity'] for item in self.cart.values()) 

    def get_total_price(self): 
     return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values()) 

    def clear(self): 
     # usunięcie koszyka 
     del self.session[settings.CART_SESSION_ID] 
     self.session.modified = True 

Next i-Datei erstellt (forms.py) und fügen Sie diesen Code:

from django import forms 

PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)] 

SIZE_CHOICES = (
    ('S', 'S'), 
    ('M', 'M'), 
    ('L', 'L'), 
    ('XL', 'XL') 
) 


class CartAddProductForm(forms.Form): 
    quantity = forms.TypedChoiceField(
           choices=PRODUCT_QUANTITY_CHOICES, 
           coerce=int) 
    update = forms.BooleanField(required=False, 
           initial=False, 
           widget=forms.HiddenInput) 
    sz = forms.MultipleChoiceField(
     required=True, 
     widget=forms.RadioSelect, 
     choices=SIZE_CHOICES, 
     initial=False) 

Mein war nächsten Schritt Ansichten erstellen

from django.shortcuts import render, redirect, get_object_or_404 
from django.views.decorators.http import require_POST 
from shop.models import Product 
from .cart import Cart 
from .forms import CartAddProductForm 


@require_POST 
def cart_add(request, product_id): 
    cart = Cart(request) 
    product = get_object_or_404(Product, id=product_id) 
    form = CartAddProductForm(request.POST) 
    if form.is_valid(): 
     cd = form.cleaned_data 
     cart.add(product=product, 
       quantity=cd['quantity'], 
       update_quantity=cd['update'], 
       size=cd['size'], 
       upd_size=['sz']) 
    return redirect('cart:cart_detail') 


def cart_remove(request, product_id): 
    cart = Cart(request) 
    product = get_object_or_404(Product, id=product_id) 
    cart.remove(product) 
    return redirect('cart:cart_detail') 


def cart_detail(request): 
    cart = Cart(request) 
    for item in cart: 
     item['update_quantity_form'] = CartAddProductForm(
         initial={'quantity': item['quantity'], 
           'update': True, 
           'size': item['size'], 
           'sz': True} 
     ) 
    return render(request, 
        'cart/detail.html', 
        {'cart': cart}) 

und die zuletzt ist thid detail.html im warenkorb app:

{% extends "shop/base.html" %} 
{% load static %} 

{% block title %}{{ product.name }}{% endblock %} 
{% block content %} 
<div class="container-fluid"> 
    <div class="row"> 
     {% for item in cart %} 
      {% with product=item.product %} 
       <div class="col-md-2"> 
        <a href="{{ product.get_absolute_url }}"> 
         <img src="{{ product.image_url }}" class="img-responsive"> 
        </a> 
       </div> 
       {{product.name}} 
       <form action="{% url 'cart:cart_add' product.id %}" method="post"> 
        {{ item.update_quantity_form.quantity }} 
        {{ item.update_quantity_form.update }} 
        <input type="submit" value="Zmień"> 
        {% csrf_token %} 
       </form> 
       {{ item.quantity }} 
       {{ item.size }} 
       <a href="{% url 'cart:cart_remove' product.id%}">Usuń</a> 
       {{item.price}} 
       {{item.total_price}} 
      {% endwith %} 
     {% endfor %} 
     {{cart.get_total_price}} 

     <a href="{% url 'orders:order_create' %}"> 
      Do kasy 
     </a> 
    </div> 
</div> 
{% endblock %} 

Ich füge Formular in poduct detail.html hinzu, um das Produkt im Warenkorb hinzuzufügen.

Was läuft falsch? Wenn ich auf "In den Warenkorb" klicke, verschiebt sich das in den Warenkorb/detail.html, aber nichts zeigt. Wenn ich alles mit Größe löschte, die Arbeit gut ist und mir Produkt im Warenkorb/detail.html ohne Größe zeige, aber ich brauche es. Wie kann ich es reparieren?

Antwort

0

In Ihren Ansichten ist ein Tippfehler enthalten.

Es sollte cd [ 'sz'], nicht [ 'sz'] sein

Es ist jetzt:

if form.is_valid(): 
    cd = form.cleaned_data 
    cart.add(product=product, 
      quantity=cd['quantity'], 
      update_quantity=cd['update'], 
      size=cd['size'], 
      upd_size=['sz']) 
return redirect('cart:cart_detail') 

Es sollte

sein
if form.is_valid(): 
    cd = form.cleaned_data 
    cart.add(product=product, 
      quantity=cd['quantity'], 
      update_quantity=cd['update'], 
      size=cd['size'], 
      upd_size=cd['sz']) 
return redirect('cart:cart_detail') 
+0

ich es tun und don‘ t Arbeit – KeepItSick

+0

Auch ich denke, Sie haben Zweck der Felder 'Größe' und 'sz' gemischt. In Ihrem CartAddProductForm sollten Sie den Feldnamen von "sz" in "size" ändern und die ursprüngliche Größe in eine gültige Größe ändern (in SIZE_CHOICES angegeben). – doggra

Verwandte Themen