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モデルに関連しています。ビューに保存PackageInfoFormして、結果をで使用する必要があると思います。show_productadd_to_cart

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