增加购物车模型
1、在goods/models.py中,新增模型CartInfos
from django.db import models
class CartInfos(models.Model):
num = models.IntegerField(verbose_name='购买数量')
user_id = models.IntegerField('用户ID')
shangpin_id = models.IntegerField('商品ID')
create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间", null=True)
update_time = models.DateTimeField(auto_now=True, verbose_name="更新时间", null=True)
def __str__(self):
return str(self.id)
class Meta:
verbose_name = '购物车'
verbose_name_plural = '购物车'
db_table = 'tb_cartinfo'
2、将模型注册到后台管理系统中,打开goods应用下的admin.py文件,添加内容如下
admin.site.register(CartInfos)
3、生成迁移文件并执行迁移, python manage.py makemigrations python manage.py migrate 查看数据库可发现新表tb_cartinfo
动态加载数据
1、在模版文件夹下的base.html,增加购物车
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>基本模版</title>
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'css/base.css' %}">
</head>
<body>
{% block top %}
{# 头部添加背景图片#}
<div style="text-align: right;height: 100px;width: 100%;background-image:url({% static 'images/backimage.jpg' %})">
{# 添加背景色#}
{# <div style="text-align: right;height: 100px;width: 100%;background: lightblue">#}
{% if user.is_authenticated %}
<div>
欢迎您:<em>{{ user.username }}</em>
<span>|</span>
<a href="{% url 'auth_app:logout' %} ">退出</a>
<span>|</span>
<a href="{% url 'auth_app:register' %}">注册</a>
<span>|</span>
<a href="{% url 'auth_app:info' %} ">用户中心</a>
<span>|</span>
<a href="{% url 'goods:index' %} ">首页</a>
<span>|</span>
<a href="{% url 'goods:carts' %} ">购物车</a>
{# <span>|</span>#}
{# <a href="{% url 'goods:myorder' %} ">我的订单</a>#}
</div>
{% endif %}
</div>
{% endblock top %}
{% block main %}
{% endblock main %}
{% block footer %}
{% endblock %}
{% block script %}
{% endblock %}
</body>
</html>
2、在goods/urls.py,添加购物车carts路径
path('carts/',views.showcart,name='carts'),
3、在goods/views.py,定义购物车视图
#显示购物车
@login_required() # 用户未登录时,转向登录界面
def showcart(request):
userid = request.COOKIES.get("userid")
carts = CartInfos.objects.filter(user_id=userid) # queryset
shangpins = []
for cart in carts:
shangpin1 = shangpin.objects.get(id=cart.shangpin_id)
shangpins.append(shangpin1)
carts_list = list(carts)
sumlist = zip(carts_list, shangpins)
return render(request, 'cart.html', {'sumlist': sumlist})
4、修改auth_app的登录视图,为当前用户添加cookie,以获取当前用户的购物车信息,cookie详细介绍参考第八章用户验证系统PPT,auth_app/views.py
#用户登录
class LoginView(View):
def get(self,request):
return render(request,"login.html")
"""用户名登录"""
def post(self, request):
username = request.POST['username']#用户名
password = request.POST['password']#密码
user = authenticate(username=username,password=password)
if user is not None:
login(request,user) # 用户登录
# return redirect(reverse('goods:index'))
res=redirect(reverse('goods:index'))
res.set_cookie('userid',user.id,max_age=60*90)
return res
else:
return render(request, 'login.html', {'account_errmsg': '用户名或密码错误'})
5、在模版下新建购物车页面cart.html,内容如下:
{% extends 'base.html' %}
{% load static %}
{% block main %}
<div style="text-align: center">
<form action="" method="post">
{% csrf_token %}
<table style="width: 80%;margin: 0 auto; table-layout: fixed;">
{#列距#}
<colgroup>
<col width="60px">
<col width="auto">
<col width="auto">
<col width="auto">
<col width="auto">
<col width="auto">
<col width="auto">
</colgroup>
<tr>
{# 全选框#}
<td style="width: 30px"><input name="allgood" type="checkbox" value=""/></td>
<td>商品</td>
<td>说明</td>
<td>单价</td>
<td>数量</td>
<td>小计</td>
<td>操作</td>
</tr>
{% for cart,good in sumlist %}
<tr >
<td style="width: 30px"><input name="" type="checkbox" value="" /></td>
<td><img src="{{ MEDIA_URL }}/{{ good.image }}" style="height: 100px;width: 100px"></td>
<td>{{ good.caption }}</td>
<td>{{ good.price }}</td>
<td>
<p>
<span>-</span>
<input value="{{ cart.num }}" disabled="disabled" style="width: 15px">
<span>+</span>
</p>
</td>
{# 某一条记录的总价#}
<td id="xiaoji">{% widthratio good.price 1 cart.num %} </td>
<td><a href="{% url 'goods:delt' cart.id %}" style="">刪除</a></td>
</tr>
{{ break }}
{% endfor %}
</table>
<a style="text-align: left">支付</a>
</form>
</div>
{% endblock %}
6、修改详情页detial.html
{% extends 'base.html' %}
{% load static %}
{% block main %}
<form action="{% url 'goods:addcart' shangpin.id %}" method="post">
{% csrf_token %}
<div class="con">
<div class="a">
<img src="{{ MEDIA_URL }}/{{ shangpin.image }}" style="width: 300px;height: 300px">
</div>
<div class="b">
<p><span>价 格 </span><strong name="huodongjia"><i>¥</i>{{ shangpin.price }}
</strong></p>
<br>
<p><span>说 明 </span>{{ shangpin.caption }}</p>
<br>
<p><span class="btn active">规 格 </span>
{% for guige in guiges %}
<label><input type="redio" value="{{ guige.name }}" name="redia{{ guige.id }}"
readonly="readonly"
style="width: 100px"></label>
<span> </span>
{% endfor %}
</p>
<br>
<p>
<span>数 量 </span>
<span id="cutnum" style="cursor: pointer;font-size: 20pt" onclick="cutnum()">-</span>
<input maxlength="4" type="" name="quantity" id="quantity" value="1" style="width: 15px"
readonly="readonly">
<span id="addnum" style="cursor: pointer;font-size: 20pt" onclick="addnum()">+</span>
</p>
<br>
<p>
<input type="submit" value="加入购物车"> <input type="submit" value="立即购买">
</p>
</div>
<div style="margin:0 auto">
<h4>详情</h4>
<div>
<img src="{{ MEDIA_URL }}/{{ shangpin.image }}" style="width: 600px;height: 600px">
</div>
</div>
</div>
</form>
{% endblock main %}
#定义了数量加减的JS方法
{% block script %}
<script type="text/javascript">
function addnum() {
var a = document.getElementById("quantity").value
document.getElementById("quantity").value = parseInt(a) + 1
}
function cutnum() {
var a = document.getElementById("quantity").value
if (parseInt(a) > 1) {
document.getElementById("quantity").value = parseInt(a) - 1
} else {
window.alert("数量最少为1")
}
}
</script>
{% endblock %}
7、同时,在goods应用下的views.py文件文件中,新增 addcart()和delt()方法
@login_required() # 用户未登录时,转向登录界面
def addcart(request, id):
# 加入购物车
quantity = request.POST.get('quantity')
userid = request.COOKIES.get('userid')
add1 = CartInfos(num=quantity, user_id=userid, shangpin_id=id)
add1.save()
# 可以返回购物车页面,也可返回详情页
shangpin1 = shangpin.objects.filter(id=id).first()
guige = Guige.objects.filter(guige_leixing_id=shangpin1.guige_leixing_id)
# 控制页面转向
return render(request, 'detail.html', {'shangpin': shangpin1, 'guiges': guige})
@login_required() # 用户未登录时,转向登录界面
def delt(request, id):
userid = request.COOKIES.get("userid")
CartInfos.objects.filter(id=id).delete() # queryset
# shangpins = shangpin.objects.all()
carts = CartInfos.objects.filter(user_id=userid)
shangpins = []
for cart in carts:
shangpin1 = shangpin.objects.get(id=cart.shangpin_id)
shangpins.append(shangpin1)
carts_list = list(carts)
sumlist = zip(carts_list, shangpins)
return render(request, 'cart.html', {'sumlist': sumlist})
8.goods/urls.py添加路径
path('addcart/<int:id>',views.addcart,name='addcart'),
path('delt/<int:id>',views.delt,name='delt'),
10、打开浏览器查看效果,点击购物车。