Django设置和检索会话数据

时间:2019-03-29 01:12:44

标签: python django session e-commerce

我正在使用Django在电子商务网站上工作。目前正在首次在django中使用会话的购物车应用程序上工作。我在设置和检索打印时为空的会话数据时遇到问题。

PS:会话中的数据将用于为用户检索购物车,或者如果该购物车是作为访客创建的,则更新购物车。

无法检索会话数据会导致每次刷新浏览器时都会创建一个新会话。

SETTINGS.PY

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # user apps
    'carts',
    'products',
    'search',
    'tags',

    # 3rd class app
    'bootstrap4',
]

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',
]

CART APP

MODELS.PY

from django.conf import settings
from django.db import models

from products.models import Product

User = settings.AUTH_USER_MODEL


class CartManager(models.Manager):
    def new(self, user=None):
        user_obj = None
        if user is not None:
            if user.is_authenticated:
                user_obj = user
        return self.model.objects.create(user=user_obj)

class Cart(models.Model):
    user        = models.ForeignKey(User, null=True, blank=True, on_delete=models.DO_NOTHING)
    products    = models.ManyToManyField(Product, blank=True)
    total       = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
    timestamp   = models.DateTimeField(auto_now_add=True)
    updated     = models.DateTimeField(auto_now=True)

    objects = CartManager()

    def __str__(self):
        return str(self.id)

VIEWS.PY

from django.shortcuts import render

from .models import Cart


def cart_home(request):
    cart_id = request.session.get('cart_id')
    qs = Cart.objects.filter(id=cart_id)
    print(cart_id, qs)
    # print(dir(request.session))
    if qs.count() == 1:
        print('Cart ID exists')
        cart_obj = qs.first()
        if request.user.is_authenticated and cart_obj.user is None:
            cart_obj.user = request.user
            cart_obj.save()
    else:
        cart_obj = Cart.objects.new(user=request.user)
        request.session['card_id']  = cart_obj.id
        # request.session.modified = True
        # print(dir(request.session))
        # print(request.session.get_expiry_age())
    return render(request, 'carts/home.html', {})

1 个答案:

答案 0 :(得分:1)

我认为您的问题可能是此行中的错字:

request.session['card_id']  = cart_obj.id

如果您仔细观察,您将设置card_id,但稍后尝试获取cart_id