Python Web框架 Django - 项目-中间件、商品详情页、添加商品到购物车

登录验证中间件middleware.py

from django.http import HttpResponseRedirect
from django.urls import reverse
from django.utils.deprecation import MiddlewareMixin
import re

from user.models import User


class LoginStatusMiddleware(MiddlewareMixin):

    def process_request(self, request):
        user_id = request.session.get('user_id')
        if user_id:
            user = User.objects.filter(pk=user_id).first()
            request.user = user
        # 过滤不需要验证的URL
        not_need_check = ['/user/register/',
                          '/user/login/',
                          '/goods/index/',
                          '/media/.*',
                          '/goods/detail/.*',
                          '/carts/add_cart/',
                          '/carts/carts/']
        path = request.path
        for not_check in not_need_check:
            if re.match(not_check, path):
                return None
        user_id = request.session.get('user_id')
        if not user_id:
            return HttpResponseRedirect(reverse('user:login'))
        user = User.objects.filter(pk=user_id).first()
        if not user:
            return HttpResponseRedirect(reverse('user:login'))
        # 获取到user,则设置全局用户对象
        request.user = user
        return None

添加商品到session的views.py

from django.http import JsonResponse
from django.shortcuts import render

from goods.models import Goods


def carts(request):
    if request.method == 'GET':
        return render(request, 'cart.html')


def add_cart(request):
    if request.method == 'POST':
        # 保存到session中
        # 1.获取前端ajax提交的商品goods_id,商品数量nums
        # 2.组装存储到session中的数据结构
        # [ [goods_id, nums, is_select], [goods_id, nums, is_select]...]
        # 3.如果加入到session中的商品已经存在于session中,则更新nums字段
        goods_id = int(request.POST.get('goods_id'))
        nums = int(request.POST.get('nums'))
        # 组装存储的结构,[商品id值, 商品数量, 商品选择状态]
        goods_list = [int(goods_id), int(nums), 1]
        # 判断session中是否保存了购物车数据, {'goods': [[goods_id, nums, 1], [goods_id, nums, 1]]
        session_goods = request.session.get('goods')
        if session_goods:
            # 修改
            flag = False
            for goods in session_goods:
                # goods为 [goods_id, nums, is_select]
                if goods[0] == goods_id:
                    goods[1] += nums
                    flag = True
            # 添加
            if not flag:
                session_goods.append(goods_list)
            request.session['goods'] = session_goods
            # session中保存的商品的个数
            goods_count = len(session_goods)
        else:
            # 第一次添加商品到session中时,保存键值对
            # 键为goods, 值为 [ [goods_id, nums, is_select] ]
            request.session['goods'] = [goods_list]
            goods_count = 1
        return JsonResponse({'code': 200, 'msg': '请求成功', 'goods_count': goods_count})

    if request.method == 'GET':
        session_goods = request.session.get('goods')
        if session_goods:
            goods_count = len(session_goods)
        else:
            goods_count = 0
        return JsonResponse({'goods_count': goods_count})

商品详情页

{% extends 'base_main.html' %}

{% block title %}
天天生鲜-商品详情
{% endblock %}

{% block pagename %}
商品详情
{% endblock %}

{% block search %}
    
{% endblock %}

{% block content %}

    

    

    

{{ goods.name }}

{{ goods.goods_brief }}

¥{{ goods.shop_price }} 单 位:500g
{% csrf_token %}
数 量:
+ -
总价:

新品推荐

  • 商品介绍
  • 评论
商品详情:
{{ goods.goods_desc | safe }}
{% endblock %} {% block js2 %} {% endblock %}

你可能感兴趣的:(Python Web框架 Django - 项目-中间件、商品详情页、添加商品到购物车)