0

我正在开发一个允许用户将模型对象添加到他们的购物车的项目,我目前正在使用 Jim McGaw 的《Beginning Django E-Commerce》一书http://www.amazon.com/exec/obidos/ASIN/1430225351/ref =nosim/liqurule-20/。我试图修改上述书中的代码以适合我的目的,但它似乎不起作用。每次我尝试添加到购物车时,我都会收到错误消息

cart_items.package_id 可能不为 NULL

我将应用程序添加到 INSTALLED_APP 元组中,我可以看到购物车甚至没有保存。只保存了 cart_id 和 date_created。

models.py (packageInfo)
from django.db import models
from django.contrib.auth.models import User


DESCRIPTION = (
    ('L', 'Leather Shoes'),
    ('E', 'Electronics'),
    ('F', 'Files'),
    )
     
class PackageInfo(models.Model):
    user            = models.ForeignKey(User, null = True)
    vendor_name     = models.CharField(max_length=100)
    description     = models.CharField(max_length = 1, choices = DESCRIPTION)
    quantity        = models.IntegerField(max_length = 10)
    total_value     = models.IntegerField(max_length = 10)
    created_at      = models.DateTimeField(auto_now_add = True)

    class Meta:
        db_table = 'packageinfo'
        ordering = ['-created_at']
    def __unicode__(self):
        return unicode (self.vendor_name)

models.py (Cart)
from django.db import models
from packageInfo.models import PackageInfo

class CartItem(models.Model):
    cart_id         = models.CharField(max_length = 50)
    date_added      = models.DateTimeField(auto_now_add = True)
    #packageinvoice  = models.ImageField(upload_to = 'invoices', help_text = '.jpg,     .png, .pdf etc')
    package         = models.ForeignKey( PackageInfo, unique = False)

    class Meta:
        db_table = 'cart_items'
        ordering = ['date_added']

cart.py (Cart)
from Cart.models import CartItem 
from packageInfo.models import PackageInfo 
from django.shortcuts import get_object_or_404 
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User


import random 
 
CART_ID_SESSION_KEY = 'cart_id' 
 
# get the current user's cart id, sets new one if blank 
def _cart_id(request): 
     if request.session.get(CART_ID_SESSION_KEY,'') == '': 
           request.session[CART_ID_SESSION_KEY] = _generate_cart_id() 
     return request.session[CART_ID_SESSION_KEY] 
 
def _generate_cart_id(): 
     cart_id = '' 
     characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()' 
     cart_id_length = 50 
     for y in range(cart_id_length): 
          cart_id += characters[random.randint(0, len(characters)-1)] 
     return cart_id 
 
# return all items from the current user's cart 
def get_cart_items(request): 
     return CartItem.objects.filter(cart_id=_cart_id(request)) 
 
# add an item to the cart 
def add_to_cart(request):
    postdata = request.POST.copy() 
     
    vendor_name = postdata.get('vendor_name','')
    description = postdata.get('description','')
    quantity = postdata.get('quantity','')
    total_value = postdata.get('total_value','')
    
    ci = CartItem()
    
    ci.vendor_name = vendor_name
    ci.description = description
    ci.quantity = quantity
    ci.total_value = total_value
    ci.cart_id = _cart_id(request) 
    ci.save() 
     
forms.py (packageInfo)

from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm
from packageInfo.models import PackageInfo


class PackageInfoForm(ModelForm):    
    class Meta:
        model = PackageInfo

    # override the default __init__ so we can set the request 
    def __init__(self, request=None, *args, **kwargs): 
        self.request = request 
        super(PackageInfoForm, self).__init__(*args, **kwargs) 
     
     # custom validation to check for cookies 
    def clean(self):         
        if self.request: 
            if not self.request.session.test_cookie_worked(): 
                raise forms.ValidationError("Cookies must be enabled.") 
        return self.cleaned_data

views.py (packageinfo)


from Cart import cart
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext, Context
from packageInfo.forms import PackageInfoForm



def show_product(request):
    if request.method == 'POST':
        postdata = request.POST.copy()
        form = PackageInfoForm(request, postdata)
        if form.is_valid():
            cart.add_to_cart(request)
            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()
            return HttpResponseRedirect('/package-information/cart/')
    else:
        form = PackageInfoForm(request=request)
    request.session.set_test_cookie()
    return render_to_response("account/package-info.html", {'form': form}, context_instance=RequestContext(request))
            
def show_cart(request): 
     cart_items = cart.get_cart_items(request) 
     return render_to_response("account/cart.html", {'cart_items': cart_items}, 
        context_instance=RequestContext(request)) 
4

1 回答 1

0

add_to_cart您设置的功能中:

ci = CartItem()

ci.vendor_name = vendor_name
ci.description = description
ci.quantity = quantity

但这些字段与 PackageInfo 模型有关。我认为您需要保存PackageInfoFormshow_product视图中并在add_to_cart.

def add_to_cart(request, package):
    ...
    ci.package = package
于 2013-01-15T13:34:50.420 回答