Django:“ SessionStore”对象没有属性“ session”

时间:2018-12-02 03:56:44

标签: django

我正在尝试根据有关Udemy的教程来构建电子商务。我在关于如何构建购物车功能(如何添加物品,查看总成本和数量)的章节中。

但是,我在将产品添加到购物车时遇到了麻烦。

/ part / add / 4 /中的

AttributeError 'SessionStore'对象没有属性'session' 请求方法:GET
要求网址:http://127.0.0.1:8000/cart/add/4/
Django版本:2.1.3
异常类型:AttributeError
异常值:
'SessionStore'对象没有属性'session'
异常位置:/home/ogonzales/Escritorio/web_proyects/perfectcushion/cart/views.py在_card_id中,第10行
Python可执行文件:/ home / ogonzales / Escritorio / projects_envs / perfectcushion_env / bin / python
Python版本:3.6.7
Python路径:
['/ home / ogonzales / Escritorio / web_proyects / perfectcushion',  '/ home / ogonzales / Escritorio / pycharm / helpers / pycharm',  '/ home / ogonzales / Escritorio / web_proyects / perfectcushion',  '/usr/lib/python36.zip',  '/usr/lib/python3.6',  '/usr/lib/python3.6/lib-dynload',  '/home/ogonzales/Escritorio/projects_envs/perfectcushion_env/lib/python3.6/site-packages',  '/home/ogonzales/Escritorio/projects_envs/perfectcushion_env/lib/python3.6/site-packages/setuptools-39.1.0-py3.6.egg',  '/home/ogonzales/Escritorio/projects_envs/perfectcushion_env/lib/python3.6/site-packages/pip-10.0.1-py3.6.egg']] 服务器时间:2018年12月2日,星期日03:17:34 +0000

views.py:

from django.shortcuts import render, redirect
from shop.models import Product
from .models import Cart, CartItem
from django.core.exceptions import ObjectDoesNotExist


# Create your views here.

def _card_id(request):
    cart = request.session.session.key
    if not cart:
        cart = request.session.create()
        return cart


def add_cart(request, product_id):
    product = Product.objects.get(id = product_id)
    try:
        cart = Cart.objects.get(cart_id = _card_id(request))
    except Cart.DoesNotExist:
        cart = Cart.objects.create(
            cart_id = _card_id(request)
        )

        cart.save()
    try:
        cart_item = CartItem.objects.get(product = product, cart = cart)
        cart_item.quantity += 1
        cart_item.save()
    except CartItem.DoesNotExist:
        cart_item = CartItem.objects.create(
            product = product,
            quantity= 1,
            cart = cart,
        )
        cart_item.save()
    return redirect('cart:cart_detail')


def cart_detail(request, total = 0, counter = 0, cart_items = None):
    try:
        cart = Cart.objects.get(cart_id = _card_id(request))
        cart_items =  CartItem.objects.filter(cart = cart, active=True)

        for cart_item in cart_items:
            total += (cart_item.product.price * cart_item.quantity)
            counter += cart_item.quantity
    except ObjectDoesNotExist:
        pass

    return render(request, 'cart.html', dict(cart_items = cart_items, total = total, counter = counter))

models.py

from django.db import models
from shop.models import Product

# Create your models here.

class Cart(models.Model):
    cart_id = models.CharField(max_length=250, blank=True)
    date_added = models.DateField(auto_now_add=True)

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

    def __str__(self):
        return self.cart_id


class CartItem(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
    quantity = models.IntegerField()
    active = models.BooleanField(default=True)
    class Meta:
        db_table = 'CartItem'

    def sub_total(self):
        return self.product.price * self.quantity

    def __str__(self):
        return self.product

跟踪

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/cart/add/4/

Django Version: 2.1.3
Python Version: 3.6.7
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'shop',
 'cart']
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']



Traceback:

File "/home/ogonzales/Escritorio/projects_envs/perfectcushion_env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/home/ogonzales/Escritorio/projects_envs/perfectcushion_env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = self.process_exception_by_middleware(e, request)

File "/home/ogonzales/Escritorio/projects_envs/perfectcushion_env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  124.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/ogonzales/Escritorio/web_proyects/perfectcushion/cart/views.py" in add_cart
  19.         cart = Cart.objects.get(cart_id = _card_id(request))

File "/home/ogonzales/Escritorio/web_proyects/perfectcushion/cart/views.py" in _card_id
  10.     cart = request.session.session.key

Exception Type: AttributeError at /cart/add/4/
Exception Value: 'SessionStore' object has no attribute 'session'

1 个答案:

答案 0 :(得分:1)

使用cart = request.session.session.key代替cart = request.session.session_key