gpt4 book ai didi

python - django:初始化对象时出现递归错误

转载 作者:行者123 更新时间:2023-12-01 03:44:41 24 4
gpt4 key购买 nike

所以我正在尝试为我的应用程序构建一个简单的购物车功能,只需添加、删除一件设备并显示当前购物车的列表。这是我的此购物车的代码:(代码主要采用 https://github.com/bmentges/django-cart )

购物车.py:

import datetime
from .models import Cart, Item, ItemManager

CART_ID = 'CART-ID'

class ItemAlreadyExists(Exception):
pass

class ItemDoesNotExist(Exception):
pass

class Cart:
def __init__(self, request, *args, **kwargs):
super(Cart, self).__init__()
cart_id = request.session.get(CART_ID)
if cart_id:
try:
cart = models.Cart.objects.get(id=cart_id, checked_out=False)
except models.Cart.DoesNotExist:
cart = self.new(request)
else:
cart = self.new(request)
self.cart = cart

def __iter__(self):
for item in self.cart.item_set.all():
yield item

def new(self, request):
cart = Cart(request, creation_date=datetime.datetime.now())
cart.save()
request.session[CART_ID] = cart.id
return cart

def add(self, equipment):
try:
item = models.Item.objects.get(
cart=self.cart,
equipment=equipment,
)
except models.Item.DoesNotExist:
item = models.Item()
item.cart = self.cart
item.equipment = equipment
item.save()
else: #ItemAlreadyExists

item.save()

def remove(self, equipment):
try:
item = models.Item.objects.get(
cart=self.cart,
equipment=equipment,
)
except models.Item.DoesNotExist:
raise ItemDoesNotExist
else:
item.delete()

def count(self):
result = 0
for item in self.cart.item_set.all():
result += 1 * item.quantity
return result


def clear(self):
for item in self.cart.item_set.all():
item.delete()

和models.py:

class Cart(models.Model):
creation_date = models.DateTimeField(verbose_name=_('creation date'))
checked_out = models.BooleanField(default=False, verbose_name=_('checked out'))

class Meta:
verbose_name = _('cart')
verbose_name_plural = _('carts')
ordering = ('-creation_date',)

def __unicode__(self):
return unicode(self.creation_date)

class ItemManager(models.Manager):
def get(self, *args, **kwargs):
if 'equipment' in kwargs:
kwargs['content_type'] = ContentType.objects.get_for_model(type(kwargs['equipment']))
kwargs['object_id'] = kwargs['equipment'].pk
del(kwargs['equipment'])
return super(ItemManager, self).get(*args, **kwargs)

class Item(models.Model):
cart = models.ForeignKey(Cart, verbose_name=_('cart'))
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()

objects = ItemManager()

class Meta:
verbose_name = _('item')
verbose_name_plural = _('items')
ordering = ('cart',)

def __unicode__(self):
return u'%d units of %s' % (self.quantity, self.equipment.__class__.__name__)

# product
def get_product(self):
return self.content_type.get_object_for_this_type(pk=self.object_id)

def set_product(self, equipment):
self.content_type = ContentType.objects.get_for_model(type(equipment))
self.object_id = equipment.pk

当尝试进入显示当前购物车的 View 时,我遇到了这个问题:

RecursionError at /calbase/cart/ maximum recursion depth exceeded in comparison

基本上它会重复调用以下内容:

cart = Cart(request, creation_date=datetime.datetime.now()) 
cart = self.new(request)
cart = Cart(request, creation_date=datetime.datetime.now())
cart = self.new(request)

......

我知道这是因为我在执行 cart = Cart(...) 时调用 init ,这再次返回到 cart = self.new(request) 并尝试了几种方法解决这个问题,徒劳。有人可以帮助我吗?

环境:

Request Method: GET
Request URL: http://127.0.0.1:8000/calbase/cart/

Django Version: 1.10
Python Version: 3.5.2
Installed Applications:
['calbase.apps.CalbaseConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'haystack',
'whoosh']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']

回溯:

File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\exception.py" in inner
39. response = get_response(request)

File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)

File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\hansong.li\Documents\GitHub\equipCal\calbase\views.py" in get_cart
72. return render_to_response('cart.html', dict(cart=Cart(request)))

File "C:\Users\hansong.li\Documents\GitHub\equipCal\calbase\cart.py" in __init__
22. cart = self.new(request)

File "C:\Users\hansong.li\Documents\GitHub\equipCal\calbase\cart.py" in __init__
22. cart = self.new(request)

File "C:\Users\hansong.li\Documents\GitHub\equipCal\calbase\cart.py" in new
30. cart = Cart(request, creation_date=datetime.datetime.now())

Exception Type: RecursionError at /calbase/cart/
Exception Value: maximum recursion depth exceeded in comparison

最佳答案

您有两个名为 Cart 的独立类。重命名其中之一。

关于python - django:初始化对象时出现递归错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39109000/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com