无法通过request.session的键获取值;我用django

时间:2019-06-08 14:12:08

标签: python django

我正在尝试使用django进行在线购物。但是我有一些问题。在制作购物车的过程中,views.py中出现错误“分配前已引用本地变量'cart_id'”。 这是这个文件:

def cart_view(request):
    try:
        cart_id = request.session['cart_id']
        cart = Cart.objects.get(id=cart_id)
        request.session['total'] = cart.items.count()
    except:
        cart = Cart()
        cart.save()
        cart_id = cart_id
        request.session['cart_id'] = cart_id
        cart = Cart.objects.get(id=cart_id)

    categories = Category.objects.all()
    return render(request, 'cart.html', locals()) 

这是回溯

Traceback:

File "C:\Users\tankr\Django_projects\django_shop\ecomapp\views.py" in product_view
  13.       cart_id = request.session['cart_id']

File "C:\Users\tankr\Django_projects\django_shop\eComEnv\lib\site-packages\django\contrib\sessions\backends\base.py" in __getitem__
  54.         return self._session[key]

During handling of the above exception ('cart_id'), another exception occurred:

File "C:\Users\tankr\Django_projects\django_shop\eComEnv\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\tankr\Django_projects\django_shop\eComEnv\lib\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\tankr\Django_projects\django_shop\eComEnv\lib\site-packages\django\core\handlers\base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\tankr\Django_projects\django_shop\ecomapp\views.py" in product_view
  19.       cart_id = cart_id

Exception Type: UnboundLocalError at /product/macbook-pro/
Exception Value: local variable 'cart_id' referenced before assignment

然后我尝试通过在功能cart_view中添加global cart_id来解决该问题,并出现另一个错误:未定义名称'cart_id'。 这是新的回溯:

Traceback:

File "C:\Users\tankr\Django_projects\django_shop_2\ecomapp\views.py" in product_view
  14.       cart_id = request.session['cart_id']

File "C:\Users\tankr\Django_projects\django_shop_2\eComEnv\lib\site-packages\django\contrib\sessions\backends\base.py" in __getitem__
  54.         return self._session[key]

During handling of the above exception ('cart_id'), another exception occurred:

File "C:\Users\tankr\Django_projects\django_shop_2\eComEnv\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\tankr\Django_projects\django_shop_2\eComEnv\lib\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\tankr\Django_projects\django_shop_2\eComEnv\lib\site-packages\django\core\handlers\base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\tankr\Django_projects\django_shop_2\ecomapp\views.py" in product_view
  20.       cart_id = cart_id

Exception Type: NameError at /product/iphone-xr-128gb/
Exception Value: name 'cart_id' is not defined

2 个答案:

答案 0 :(得分:2)

cart_id = cart_id 行没有意义,我想使用cart.id,甚至更安全的cart.pk

def cart_view(request):
    try:
        cart_id = request.session['cart_id']
        cart = Cart.objects.get(id=cart_id)
    except (KeyError, Cart.DoesNotExist):
        cart = Cart.objects.create()
        request.session['cart_id'] = cart_id = cart.pk
        request.session['total'] = 0
    else:
        request.session['total'] = cart.items.count()
    categories = Category.objects.all()
    return render(request, 'cart.html', locals())

不要使用locals()。从软件设计的角度来看,这不是一个好习惯。这确实意味着您不知道传递给模板的内容。如果您要酸性地创建一个与上下文处理器中的变量名称相同的变量,则可能会出现意想不到的行为。

答案 1 :(得分:0)

问题是您的try块未执行,并且在存在cart_id = cart_id的地方开始执行block,这就是为什么您会出错。

您可以在现有代码中执行类似的操作

def cart_view(request):
    cart_id = request.session['cart_id']                     # before try block
    try:
        cart = Cart.objects.get(id=cart_id)
        request.session['total'] = cart.items.count()
    except:
        cart = Cart()
        cart.save()
        cart_id = cart_id
        request.session['cart_id'] = cart_id
        cart = Cart.objects.get(id=cart_id)

    categories = Category.objects.all()
    return render(request, 'cart.html', locals())