day52-Django项目-天天生鲜

一、商品详情模块

1.在urls.py文件中定义路由

from django.conf.urls import url, include

from goods import views

urlpatterns = [
    # 首页
    url(r'index/', views.index, name='index'),
    # 商品详情
    url(r'^detail/(\d+)/', views.detail, name='detail'),
]

2.查看商品详情功能

def detail(request, id):
    if request.method == 'GET':
        goods = Goods.objects.get(pk=id)
        return render(request, 'detail.html', {'goods': goods})

3.detail.html

{% extends 'base_main.html' %}

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

{% block search %}
    {% load  static %}
    
{% endblock %}

{% block content %}
    

    

    

{{ goods.name }}

{{ goods.goods_brief }}

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

新品推荐

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

二、添加商品到购物车模块

1.在urls.py文件中定义路由

from django.conf.urls import url, include

from carts import views

urlpatterns = [
    # 购物车页面
    url(r'^cart/', views.cart, name='cart'),
    # 加入购物车
    url(r'^add_cart/', views.add_cart, name='add_cart'),
]

2.添加商品到购物车功能

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


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


def add_cart(request):
    if request.method == 'GET':
        session_goods = request.session.get('goods')
        goods_count = len(session_goods)
        return JsonResponse({'code': 200, 'msg': '请求成功', 'goods_count': goods_count})

    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': [[id, nums, 1], [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,值为[[id, nums, is_select], [id, nums, is_select]]
            request.session['goods'] = [goods_list]
            goods_count = 1
        return JsonResponse({'code': 200, 'msg': '请求成功', 'goods_count': goods_count})

3.前端页面Ajax提交商品信息代码

 {% csrf_token %}
    
    

你可能感兴趣的:(day52-Django项目-天天生鲜)