保姆级教程,手把手教你如何使用Django完成母婴商城项目:(六)商品信息模块

本文介绍了如何使用Django实现商品列表页和详细页的功能,包括商品分类、排序、搜索、分页以及收藏。在商品列表页中,通过GET参数筛选商品并进行分页显示。商品详情页展示了商品的详细信息,如价格、销量,并提供了相关商品推荐。同时,实现了商品收藏功能,用户可以通过点击收藏按钮将商品添加到收藏列表。
摘要由CSDN通过智能技术生成

一、商品列表页

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>&nbsp;&nbsp;&nbsp;&nbsp;</span><strong class="address">广东&nbsp;&nbsp;广州&nbsp;&nbsp;天河区</strong></p>
            </div>
            <div class="choose-attrs">
              <div class="color layui-clear"><span class="title">&nbsp;&nbsp;&nbsp;&nbsp;</span> <div class="color-cont"><span class="btn active">{{ commoditys.sezes }}</span></div></div>
              <div class="number layui-clear"><span class="title">&nbsp;&nbsp;&nbsp;&nbsp;</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.pyviews.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)

四、运行测试

在首页或者商品页点击商品出现详细商品页面就代表到目前为止一切顺利啦:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值