登录验证中间件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 %}
<div class="search_bar clearfix">
<a href="{% url 'goods:index' %}" class="logo fl"><img src="/static/images/logo.png"></a>
<div class="search_con fl">
<input type="text" class="input_text fl" name="" placeholder="搜索商品">
<input type="button" class="input_btn fr" name="" value="搜索">
</div>
<div class="guest_cart fr">
<a href="{% url 'carts:cart' %}" class="cart_name fl">我的购物车</a>
<div class="goods_count fl" id="show_count">0</div>
</div>
</div>
{% endblock %}
{% block content %}
<div class="navbar_con">
<div class="navbar clearfix">
<div class="subnav_con fl">
<h1>全部商品分类</h1>
<span></span>
<ul class="subnav">
<li><a href="#" class="fruit">新鲜水果</a></li>
<li><a href="#" class="seafood">海鲜水产</a></li>
<li><a href="#" class="meet">猪牛羊肉</a></li>
<li><a href="#" class="egg">禽类蛋品</a></li>
<li><a href="#" class="vegetables">新鲜蔬菜</a></li>
<li><a href="#" class="ice">速冻食品</a></li>
</ul>
</div>
<ul class="navlist fl">
<li><a href="{% url 'goods:index' %}">首页</a></li>
<li class="interval">|</li>
<li><a href="">手机生鲜</a></li>
<li class="interval">|</li>
<li><a href="">抽奖</a></li>
</ul>
</div>
</div>
<div class="breadcrumb">
<a href="#">全部分类</a>
<span>></span>
<a href="#">{{ category }}</a>
<span>></span>
<a href="#">商品详情</a>
</div>
<div class="goods_detail_con clearfix">
<div class="goods_detail_pic fl"><img src="/media/{{ goods.goods_front_image }}"></div>
<div class="goods_detail_list fr">
<h3>{{ goods.name }}</h3>
<p>{{ goods.goods_brief }}</p>
<div class="prize_bar">
<span class="show_pirze">¥<em id="price">{{ goods.shop_price }}</em></span>
<span class="show_unit">单 位:500g</span>
</div>
<div class="goods_num clearfix">
{% csrf_token %}
<div class="num_name fl">数 量:</div>
<div class="num_add fl">
<input style="display: none" id="goods_num" value="{{ goods.goods_nums }}">
<input type="text" class="num_show fl" id="num" value="1">
<a href="javascript:;" class="add fr" id="add">+</a>
<a href="javascript:;" class="minus fr" id="minus">-</a>
</div>
</div>
<div class="total">总价:<em><span id="total"></span>元</em></div>
<div class="operate_btn">
<a href="javascript:;" class="buy_btn">立即购买</a>
<a href="javascript:;" class="add_cart" onclick="add_to_cart({{ goods.id }})">加入购物车</a>
</div>
</div>
</div>
<div class="main_wrap clearfix">
<div class="l_wrap fl clearfix">
<div class="new_goods">
<h3>新品推荐</h3>
<ul>
<li>
<a href="#"><img src="/static/images/goods/goods001.jpg"></a>
<h4><a href="#">进口柠檬</a></h4>
<div class="prize">¥3.90</div>
</li>
<li>
<a href="#"><img src="/static/images/goods/goods002.jpg"></a>
<h4><a href="#">玫瑰香葡萄</a></h4>
<div class="prize">¥16.80</div>
</li>
</ul>
</div>
</div>
<div class="r_wrap fr clearfix">
<ul class="detail_tab clearfix">
<li class="active">商品介绍</li>
<li>评论</li>
</ul>
<div class="tab_content">
<dl>
<dt>商品详情:</dt>
<dd>{{ goods.goods_desc | safe }}</dd>
</dl>
</div>
</div>
</div>
<div class="add_jump"></div>
{% endblock %}
{% block js2 %}
<script type="text/javascript" src="/static/js/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
var goods_num = $('#goods_num').val()
function total(){
$('#total').text(parseInt($('#num').val()) * parseInt($('#price').text()))
}
total()
$('#total').text(parseInt($('#num').val()) * parseInt($('#price').text()))
$('#add').on('click', function () {
var num = parseInt($('#num').val())
if(num < goods_num){
$('#num').val(num + 1)
total()
}
})
$('#minus').on('click', function () {
var num = parseInt($('#num').val())
if(num > 1){
$('#num').val(num - 1)
total()
}
})
$('#num').change(function () {
var num = $('#num').val()
if(parseInt(num) > 0 && num != '' && parseInt(num) <= goods_num){
total()
}else{
alert('数量必须大于0且少于库存')
$('#num').val(1)
total()
}
})
function add_to_cart(id) {
var nums = $('#num').val();
var csrf = $('input[name="csrfmiddlewaretoken"]').val();
$.ajax({
url: '/carts/add_cart/',
data: {
'goods_id': id,
'nums': nums,
},
type: 'POST',
dataType: 'JSON',
headers: {'X-CSRFToken': csrf},
success: function (data) {
if(data.code == 200){
$('#show_count').text(data.goods_count)
}
},
error: function (data) {
alert('失败')
}
})
}
$(function () {
$.ajax({
url: '/carts/add_cart/',
type: 'GET',
dataType: 'JSON',
success: function (data) {
$('#show_count').text(data.goods_count)
},
error: function (data) {
alert('失败')
}
})
})
</script>
{% endblock %}