一、商品列表页
1、定义视图函数 commodityView :
from django.shortcuts import render
from django.core.paginator import Paginator
from django.core.paginator import EmptyPage
from django.core.paginator import PageNotAnInteger
from .models import *
def commodityView(request):
title = '商品列表'
classContent = 'commoditys'
# 根据模型Types生成商品分类列表
firsts = Types.objects.values('firsts').distinct()
typesList = Types.objects.all()
# 获取请求参数
t = request.GET.get('t', '')
s = request.GET.get('s', 'sold')
p = request.GET.get('p', 1)
n = request.GET.get('n', '')
# 根据请求参数查询商品信息
commodityInfos = CommodityInfos.objects.all()
if t:
types = Types.objects.filter(id=t).first()
commodityInfos = commodityInfos.filter(types=types.seconds)
if s:
commodityInfos = commodityInfos.order_by('-' + s)
if n:
commodityInfos = commodityInfos.filter(name__contains=n)
# 分页功能
paginator = Paginator(commodityInfos, 6)
try:
pages = paginator.page(p)
except PageNotAnInteger:
pages = paginator.page(1)
except EmptyPage:
pages = paginator.page(paginator.num_pages)
return render(request, 'commodity.html', locals())
2、商品列表页的数据渲染
打开模板文件 commodity.html
,更新代码:
{% extends 'base.html' %}
{% load static %}
{% block content %}
<div class="commod-cont-wrap">
<div class="commod-cont w1200 layui-clear">
<div class="left-nav">
<div class="title">所有分类</div>
<div class="list-box">
{% for f in firsts %}
<dl>
<dt>{{ f.firsts }}</dt>
{% for t in typesList %}
{% if t.firsts == f.firsts %}
<dd><a href="{% url 'commodity:commodity' %}?t={{ t.id }}&n={{ n }}">{{ t.seconds }}</a></dd>
{% endif %}
{% endfor %}
</dl>
{% endfor %}
</div>
</div>
<div class="right-cont-wrap">
<div class="right-cont">
<div class="sort layui-clear">
<a {% if not s or s == 'sold' %}class="active" {% endif %} href="{% url 'commodity:commodity' %}?t={{ t }}&s=sold&n={{ n }}">销量</a>
<a {% if s == 'price' %}class="active" {% endif %} href="{% url 'commodity:commodity' %}?t={{ t }}&s=price&n={{ n }}">价格</a>
<a {% if s == 'created' %}class="active" {% endif %} href="{% url 'commodity:commodity' %}?t={{ t }}&s=created&n={{ n }}">新品</a>
<a {% if s == 'likes' %}class="active" {% endif %} href="{% url 'commodity:commodity' %}?t={{ t }}&s=likes&n={{ n }}">收藏</a>
</div>
<div class="prod-number">
<a href="javascript:;">商品列表</a>
<span>></span>
<a href="javascript:;">共{{ commodityInfos|length }}件商品</a>
</div>
<div class="cont-list layui-clear" id="list-cont">
{% for p in pages.object_list %}
<div class="item">
<div class="img">
<a href="{% url 'commodity:detail' p.id %}">
<img height="280" width="280" src="{{ p.img.url }}"></a>
</div>
<div class="text">
<p class="title">{{ p.name }}</p>
<p class="price">
<span class="pri">¥{{ p.price|floatformat:'2' }}</span>
<span class="nub">{{ p.sold }}付款</span>
</p>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
<div id="demo0" style="text-align: center;">
<div class="layui-box layui-laypage layui-laypage-default" id="layui-laypage-1">
{% if pages.has_previous %}
<a href="{% url 'commodity:commodity' %}?t={{ t }}&s={{ s }}&n={{ n }}&p={{ pages.previous_page_number }}" class="layui-laypage-prev">上一页</a>
{% endif %}
{% for page in pages.paginator.page_range %}
{% if pages.number == page %}
<span class="layui-laypage-curr"><em class="layui-laypage-em"></em><em>{{ page }}</em></span>
{% elif pages.number|add:'-1' == page or pages.number|add:'1' == page %}
<a href="{% url 'commodity:commodity' %}?t={{ t }}&s={{ s }}&n={{ n }}&p={{ page }}">{{ page }}</a>
{% endif %}
{% endfor %}
{% if pages.has_next %}
<a href="{% url 'commodity:commodity' %}?t={{ t }}&s={{ s }}&n={{ n }}&p={{ pages.pages.next_page_number }}" class="layui-laypage-next">下一页</a>
{% endif %}
</div>
</div>
</div>
</div>
{% endblock content %}
{% block script %}
layui.config({
base: '{% static 'js/' %}'
}).use(['mm','laypage','jquery'],function(){
var laypage = layui.laypage,$ = layui.$,
mm = layui.mm;
$('.list-box dt').on('click',function(){
if($(this).attr('off')){
$(this).removeClass('active').siblings('dd').show()
$(this).attr('off','')
}else{
$(this).addClass('active').siblings('dd').hide()
$(this).attr('off',true)
}
})
});
{% endblock script %}
然后你就可以通过点击首页里面的所有商品进入商品页面了。
二、商品详细页
1、定义视图函数
首先实现商品详细页的数据展示,打开项目应用 commodity 的 views.py 定义视图函数,直接在视图页面后面添加这些代码就行:
def detailView(request, id):
title = '商品介绍'
classContent = 'datails'
commoditys = CommodityInfos.objects.filter(id=id).first()
items = CommodityInfos.objects.exclude(id=id).order_by('-sold')[:5]
likesList = request.session.get('likes', [])
likes = True if id in likesList else False
return render(request, 'details.html', locals())
2、商品详细页的数据渲染
打开 details.html
:
{% extends 'base.html' %}
{% load static %}
{% block content %}
<div class="data-cont-wrap w1200">
<div class="crumb">
<a href="{% url 'index:index' %}">首页</a>
<span>></span>
<a href="{% url 'commodity:commodity' %}">所有商品</a>
<span>></span>
<a href="javascript:;">产品详情</a>
</div>
<div class="product-intro layui-clear">
<div class="preview-wrap">
<img height="300" width="300" src="{{ commoditys.img.url }}">
</div>
<div class="itemInfo-wrap">
<div class="itemInfo">
<div class="title">
<h4>{{ commoditys.name }}</h4>
{% if likes %}
<span id="collect"><i class="layui-icon layui-icon-rate-solid"></i>收藏</span>
{% else %}
<span id="collect"><i class="layui-icon layui-icon-rate"></i>收藏</span>
{% endif %}
</div>
<div class="summary">
<p class="reference"><span>参考价</span> <del>¥{{ commoditys.price|floatformat:'2' }}</del></p>
<p class="activity"><span>活动价</span><strong class="price"><i>¥</i>{{ commoditys.discount|floatformat:'2' }}</strong></p>
<p class="address-box"><span>送 至</span><strong class="address">广东 广州 天河区</strong></p>
</div>
<div class="choose-attrs">
<div class="color layui-clear"><span class="title">规 格</span> <div class="color-cont"><span class="btn active">{{ commoditys.sezes }}</span></div></div>
<div class="number layui-clear"><span class="title">数 量</span><div class="number-cont">
<span class="cut btn">-</span>
<input onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" maxlength="4" type="" id="quantity" value="1">
<span class="add btn">+</span></div></div>
</div>
<div class="choose-btns">
<a class="layui-btn layui-btn-danger car-btn">
<i class="layui-icon layui-icon-cart-simple"></i>加入购物车</a>
</div>
</div>
</div>
</div>
<div class="layui-clear">
<div class="aside">
<h4>热销推荐</h4>
<div class="item-list">
{% for item in items %}
<div class="item">
<a href="{% url 'commodity:detail' item.id %}">
<img height="280" width="280" src="{{ item.img.url }}">
</a>
<p>
<span title="{{ item.name }}">
{% if item.name|length > 15 %}
{{ item.name|slice:":15" }}...
{% else %}
{{ item.name|slice:":15" }}
{% endif %}
</span>
<span class="pric">¥{{ item.discount|floatformat:'2' }}</span>
</p>
</div>
{% endfor %}
</div>
</div>
<div class="detail">
<h4>详情</h4>
<div class="item">
<img width="800" src="{{ commoditys.details.url }}">
</div>
</div>
</div>
</div>
{% endblock content %}
{% block script %}
layui.config({
base: '{% static 'js/' %}'
}).use(['mm','jquery'],function(){
var mm = layui.mm,$ = layui.$;
var cur = $('.number-cont input').val();
$('.number-cont .btn').on('click',function(){
if($(this).hasClass('add')){
cur++;
}else{
if(cur > 1){
cur--;
}
}
$('.number-cont input').val(cur)
})
$('.layui-btn.layui-btn-danger.car-btn').on('click',function(){
var quantity = $("#quantity").val();
window.location = "{% url 'shopper:shopcart' %}?id={{ commoditys.id }}&quantity=" + quantity
});
$('#collect').on('click',function(){
var url = "{% url 'commodity:collect' %}?id={{ commoditys.id }}"
$.get(url ,function(data,status){
if (data.result=="收藏成功"){
$('#collect').find("i").removeClass("layui-icon-rate")
$('#collect').find("i").addClass("layui-icon-rate-solid")
}
alert(data.result);
});
});
});
{% endblock script %}
三、商品收藏
在 commodity 的 urls.py
和 views.py
定义路由 collect 及其视图函数 colloectView :
# 项目应用 commodity 的 urls.py
from django.urls import path
from .views import *
urlpatterns = [
path('.html', commodityView, name='commodity'),
path('/detail.<int:id>.html', detailView, name='detail'),
path('/collect.html', collectView, name='collect')
]
# 项目应用 commodity 的 views.py
from django.http import JsonResponse
from django.db.models import F
def collectView(request):
id = request.GET.get('id', '')
result = {"result": "已收藏"}
likes = request.session.get('likes', [])
if id and not int(id) in likes:
# 对商品的收藏数量执行自增加1
CommodityInfos.objects.filter(id=id).update(likes=F('likes')+1)
result['result'] = "收藏成功"
request.session['likes'] = likes + [int(id)]
return JsonResponse(result)
四、运行测试
在首页或者商品页点击商品出现详细商品页面就代表到目前为止一切顺利啦: