在本次的项目主要渲染了商品详情页面,购物车页面;
主要运用了用中间件检测登陆状态;用ajax异步请求传输数据,用session接收数据;退出等知识
1退出
删除session中的cookies的方式
方法一:request.session.flush()
方法二:del request.session['user_id']
def logout(request):
if request.method == 'GET':
删除session中的键值对user_id
# request.session.flush()
del request.session['user_id']
return HttpResponseRedirect(reverse('goods:index'))
2中间件检测登陆状态
user_id = request.session.get('user_id')
user = User.objects.filter(pk=user_id).first();给request.user属性赋值,赋值为当前登陆系统的用户
request.user = user ;请求中的用户属性改为当前登陆用户对象
{{ request.user.username }}:前端利用session解析登陆用户
class LoggingMiddleware(MiddlewareMixin):
def process_request(self, request):
try:
user_id = request.session.get('user_id')
if user_id:
user = User.objects.filter(pk=user_id).first()
request.user = user
return None
except Exception as e:
return HttpResponseRedirect(reverse('goods:index'))
def process_response(self, request, response):
return response
3商品详情页面
views文件中内容
def detail(request, id):
if request.method == 'GET':
good = Goods.objects.filter(pk=id).first()
return render(request, 'detail.html', {'good': good})
urls文件中内容
path('detail/<int:id>/', views.detail, name='detail'),
html页面内容
<a href="{% url 'goods:detail' i.id %}"><img src="/media/{{ i.goods_front_image }}"></a>
商品页面加减按钮添加商品数命函数
<a href="javascript:;" class="add fr" onclick="add_goods()">+</a>
<script>
function add_goods(){
var num = $('.num_show').val()
var new_num = parseInt(num) + 1
$('.num_show').val(new_num)
}
</script>
<a href="javascript:;" class="minus fr" onclick="sub_goods()">-</a>
<script>
function sub_goods(){
var num = $('.num_show').val()
if(parseInt(num) >1 ){
var new_num = parseInt(num) - 1
$('.num_show').val(new_num)
}
}
</script>
利用ajax异步请求(原生写法)将选取的商品加入购物车并将选取的商品种类渲染到页面
$.ajax({ });ajax异步请求;请求的路由,请求类型,data数据有哪些参数,数据格式,请求成功做什么,失败又做什么
<a href="javascript:;" class="add_cart" id="add_cart"
onclick="add_cart({{ good.id }})">加入购物车</a>
{% csrf_token %}
<script>
{#ajax异步请求#}
function add_cart(id){
var num = $('.num_show').val()
var csrf = $('input[name="csrfmiddlewaretoken"]').val()
$.ajax({
url:'/cart/add_cart/',
type:'POST',
data:{'goods_id':id, 'goods_num':num},
headers:{'X-CSRFToken': csrf},
dataType:'json',
success:function (data) {
console.log(data)
{#如果状态码为200,就将请求后的商品数量赋给购物车显示的商品数量#}
if(data.code == '200'){
$('#show_count').text(data.count)
}
},
error: function (data) {
alert('失败')
}
})
}
</script>
views文件中定义ajax异步请求传入的数据对应的处理函数,将商品添加到购物车
第一次添加时给session设置键和值, 给session设值为一个列表
request.session['goods'] = [goods_list]
def add_cart(request):
if request.method == 'POST':
接收商品id值和商品数量num
组装存储的商品格式:[good_id,num,is_select]
组装多个商品格式[[good_id,num,is_select],[good_id,num,is_select]]
goods_id = int(request.POST.get('goods_id'))
goods_num = int(request.POST.get('goods_num'))
goods_list = [goods_id, goods_num, 1]
session_goods = request.session.get('goods')
if session_goods:
1.添加重复的商品,则修改
flag = True
for se_goods in session_goods:
if se_goods[0] == goods_id:
se_goods[1] += goods_num
flag = False
if flag:
2.添加的商品不存在于购物车中,则新增商品
session_goods.append(goods_list)
request.session['goods'] = session_goods
count = len(session_goods)
else:
为else表明第一次添加购物车,需组装购物车中商品格式为
# [[good_id,num,is_select],[good_id,num,is_select]]
第一次添加时给session设置键和值
request.session['goods'] = [goods_list]
count = 1
return JsonResponse({'code': 200, 'msg': '请求成功', 'count': count})
4更新导航栏购物车显示商品数量
ajax写法二(简写)更新商品统计数量
$.get('/cart/cart_num/', function (data) { })ajax异步请求的路由,(此次为get请求方式)以及函数
<div class="goods_count fl" id="show_count">1(待更新内容)</div>
<script>
用于渲染购物车的数量
$.get('/cart/cart_num/', function (data) {
if(data.code == '200'){
$('#show_count').text(data.count)
}
})
</script>
统计商品件数
def cart_num(request):
if request.method == 'GET':
session_goods = request.session.get('goods')
if session_goods:
count = len(session_goods)
else:
count = 0
return JsonResponse({'code': 200, 'msg': '请求成功', 'count': count})
5跳转购物车界面
对购物车中的商品信息进行渲染
def cart(request):
if request.method == 'GET':
session_goods = request.session.get('goods')
result = []
组装返回格式:[objects1,objects2]
objects ---> [物品对象, 是否选中, 数量 ,某种物品总价]
for se_goods in session_goods:
# se_goods --> [good_id,num,is_select]
goods = Goods.objects.filter(pk=se_goods[0]).first()
total_price = goods.shop_price * se_goods[1]
data = [goods, se_goods[1], se_goods[2], total_price]
result.append(data)
return render(request, 'cart.html', {'result': result})
5.1对商品数量总价进行统计
def cart_price(request):
if request.method == 'GET':
session_goods = request.session.get('goods')
总的商品件数
all_total = len(session_goods) if session_goods else 0
all_price = 0
is_select_num = 0
for se_goods in session_goods:
如果选中
if se_goods[2]:
goods = Goods.objects.filter(pk=se_goods[0]).first()
all_price += goods.shop_price * se_goods[1]
is_select_num += 1
return JsonResponse({'code': 200, 'msg': '请求成功', 'all_total': all_total,
'all_price': all_price, 'is_select_num': is_select_num})
刷新商品价格及件数
$('.total_count em').html(data.all_total)选中class属性为total_count下的class属性为c0103下的em标签并为其赋值data.all_total
<script>
function cart_price() {
$.get('/cart/cart_price/', function (data) {
if(data.code == '200'){
$('.total_count em').html(data.all_total)
$('.settlements .col03 em').html(data.all_price)
$('.settlements .col03 b').html(data.is_select_num)
}
})
}
cart_price()
</script>
5.2改变商品数量及价格
def change_cart(request):
if request.method == 'POST':
修改商品的数量和选择状态
其实就是修改session中商品信息,结构为[goods_id,num,is_select]
1.获取商品id值和数量或选择状态
goods_id = int(request.POST.get('goods_id'))
goods_num = request.POST.get('goods_num')
goods_select = request.POST.get('goods_select')
2.修改
session_goods = request.session.get('goods')
for se_goods in session_goods:
if se_goods[0] == goods_id:
se_goods[1] = int(goods_num) if goods_num else se_goods[1]
se_goods[2] = int(goods_select) if goods_select else se_goods[2]
request.session['goods'] = session_goods
return JsonResponse({'code': 200, 'msg': '请求成功'})
ajax修改数量或者选择状态
function add_cart(id) {
var num = $('#num_show_' + id).val()
var new_num = parseInt(num) + 1
$('#num_show_' + id).val(new_num)
change_cart(id, new_num)
}
{#减少商品数量#}
function sub_cart(id) {
var num = $('#num_show_' + id).val()
if(parseInt(num) > 1){
var new_num = parseInt(num) - 1
$('#num_show_' + id).val(new_num)
change_cart(id, new_num)
}
}
{#修改数量或选择状态#}
function change_cart(id, new_num) {
var csrf = $('input[name="csrfmiddlewaretoken"]').val()
$.ajax({
url:'/cart/change_cart/',
type:'POST',
data:{'goods_id':id, 'goods_num':new_num},
headers:{'X-CSRFToken':csrf},
dataType:'json',
success:function (data) {
{#刷新价格及件数#}
$.get('/cart/cart_price/', function (data) {
if(data.code == '200'){
$('.total_count em').html(data.all_total)
$('.settlements .col03 em').html(data.all_price)
$('.settlements .col03 b').html(data.is_select_num)
}
})
},
error:function (data) {
alert('修改失败')
}
})
}
网友评论