开源web框架django知识总结(二十一)

Posted 主打Python

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了开源web框架django知识总结(二十一)相关的知识,希望对你有一定的参考价值。

开源web框架django知识总结(二十一)

1.请求方式

选项方案
请求方法GET
请求地址/orders/info/(?P<page_num>\\d+)/

2.请求参数:路径参数

参数名类型是否必传说明
page_numint当前页码

3.响应结果:HTML

user_center_order.html

4.后端接口定义和实现orders.views.py

class UserOrderInfoView(View):

    @method_decorator(login_required)
    def get(self, request, page):
        """提供我的订单页面"""
        user = request.user
        page = request.GET.get('page')
        page_size = request.GET.get('page_size')
        # 查询订单
        orders = user.orderinfo_set.all().order_by("-create_time")

        # 2、分页 —— 根据page和page_size分页
        # 使用django的接口对一个模型类查询集分页
        # 实例化一个分页器对象,传入skus被分页对目标数据(查询集),传入page_size来指定按照每页几个划分
        paginator = Paginator(orders, page_size)
        try:
            # 分页器对象.page函数调用传入page表示获取第几页
            # 返回值是一个查询集,表示当前页数据查询集
            page_orders = paginator.page(page)

        except EmptyPage as e:
            print(e)
            return JsonResponse('code': 400, 'errmsg': '订单不存在')

        ret_list1 = []
        ret_list2 = []

        for order in page_orders:
            # 绑定订单状态
            order.status_name = OrderInfo.ORDER_STATUS_CHOICES[order.status - 1][1]
            # 绑定支付方式
            order.pay_method_name = OrderInfo.PAY_METHOD_CHOICES[order.pay_method - 1][1]
            # 订单创建时间
            # 订单id
            order_id = OrderInfo.order_id
            time = OrderInfo.objects.filter(order_id=order).values('create_time').get()
            time = str(time.get('create_time'))[:19]
            # 订单id
            order.id = str(order_id)
            total_count = order.total_count
            total_amount = order.total_amount

            ret_list1.append(
                'time': time,
                'order_id': str(order),
                'total_count': total_count,
                'total_amount': total_amount,
                'status_name': order.status_name,
                'status': order.status,  # 增
                'pay_method_name': order.pay_method_name,
            )
        print(type(ret_list1[0].get('order_id')))
        order_id = ret_list1[0].get('order_id')

        # 查询订单商品
        sku_ids = OrderGoods.objects.all().filter(order_id=int(order_id))
        # 遍历订单商品
        for sku_id in sku_ids:
            # sku_id = sku_id.get('sku_ids')
            price = sku_id.price
            count = sku_id.count
            amount = price * count
            name = sku_id.sku.name  # 增
            image_url = 'http://192.168.42.128:8888/' + str(sku_id.sku.default_image_url)

            ret_list2.append(
                'image_url': image_url,
                'price': price,
                'count': count,
                'amount': amount,
                'name': name[:20],  # 增
            )

        # 3、构建响应返回
        return JsonResponse(
            'code': 0,
            'errmsg': 'ok',
            'ret_list1': ret_list1,
            'ret_list2': ret_list2,
            'count': paginator.num_pages,  # 总页数
        )
        )

orders.urls.py

from django.urls import re_path
from . import views

urlpatterns = [
    re_path(r'^orders/settlement/$', views.OrderSettlementView.as_view()),
    re_path(r'^orders/commit/$', views.OrderCommitView.as_view()),
    re_path(r'^orders/info/(?P<page>\\d+)/$',views.UserOrderInfoView.as_view())
]

新建user_center_order.js

var vm = new Vue(
        el:'#app',
        // delimiters: ['[[', ']]'], // 修改vue模板符号,防止与django冲突
        data:
            host: host,
            username: '',
            user_id: sessionStorage.user_id || localStorage.user_id,
            token: sessionStorage.token || localStorage.token,
            page: 1, // 当前页数
            page_size: 1, // 每页数量
            count: 0,  // 总数量
            skus: [], // 数据
            orderinfos: [], // 数据
            order_id: '',  //增
            status: '',  //,
        computed: 
        total_page: function()  // 总页数
            // return Math.ceil(this.count/this.page_size);
            return this.count;
        ,
        next: function()  // 下一页
            if (this.page >= this.total_page) 
                return 0;
             else 
                return this.page + 1;
            
        ,
        previous: function()  // 上一页
            if (this.page <= 0 ) 
                return 0;
             else 
                return this.page - 1;
            
        ,
        page_nums: function()  // 页码
            // 分页页数显示计算
            // 1.如果总页数<=5
            // 2.如果当前页是前3// 3.如果当前页是后3,
            // 4.既不是前3页,也不是后3页
            var nums = [];
            if (this.total_page <= 5) 
                for (var i=1; i<=this.total_page; i++)
                    nums.push(i);
                
             else if (this.page <= 3) 
                nums = [1, 2, 3, 4, 5];
             else if (this.total_page - this.page <= 2) 
                for (var i=this.total_page; i>this.total_page-5; i--) 
                    nums.push(i);
                
             else 
                for (var i=this.page-2; i<this.page+3; i++)
                    nums.push(i);
                
            
            return nums;
        
    ,
        mounted: function()
        this.username = getCookie('username');

        this.page_num = this.get_query_string('page_num');

        this.get_orderinfos();

    ,

     methods: 
        // 退出登录按钮
        logoutfunc: function () 
            var url = this.host + '/logout/';
            axios.delete(url, 
                responseType: 'json',
                withCredentials:true,
            )
                .then(response => 
                    location.href = 'login.html';
                )
                .catch(error => 
                    console.log(error.response);
                )
        ,
         // 获取url路径参数
        get_query_string: function(name)
            var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
            var r = window.location.search.substr(1).match(reg);
            if (r != null) 
                return decodeURI(r[2]);
            
            return null;
        ,
        // 请求商品数据
        get_orderinfos: function()
            var url = this.host+'/orders/info/'+this.page
            axios.get(url, 
                    params: 
                        page: this.page,
                        page_size: this.page_size,
                    ,
                    responseType: 'json',
                    withCredentials:true
                )
                .then(response => 
                    this.count = response.data.count;
                    this.orderinfos = response.data.ret_list1;
                    this.skus = response.data.ret_list2;
                    console.log(this.skus );
                    this.order_id =this.orderinfos[0].order_id;//增
                    this.status =this.orderinfos[0].status;//)
                .catch(error => 
                    console.log(error);
                )
        ,
        // 点击页数
        on_page: function(num)
            if (num != this.page)
                this.page = num;
                this.get_orderinfos();
            
        ,
        //增
        oper_btn_click:function(order_id, status)
            var order_id = this.orderinfos[0].order_id;
            var status = this.orderinfos[0].status;
            console.log(status)
            if (status == '1') 
                // 待支付
                let url = this.host+'/payment/' + order_id + '/';
                axios.get(url, 
                    responseType: 'json',
                    withCredentials:true
                )
                    .then(response => 

                        if (response.data.code == '0') 
                            location.href = response.data.alipay_url;
                         else if (response.data.code == '4101') 
                            location.href = '/login/?next=/orders/info/1/';
                         else 
                            console.log(response.data);
                            alert(response.data.errmsg);
                        
                    )
                    .catch(error => 
                        console.log(error.response);
                    );
             else if (status == '4') 
                // 待评价
                location.href = '/goods_judge.html?order_id=' + order_id;
             else 
                // console.log(response.data.code)
                // 其他:待收货...
                location.href = '/';

            
        ,

    
    )

user_center_order.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
	<title>阿尔法商城-用户中心</title>
	<link rel="stylesheet" type="text/css" href="css/reset.css">
	<link rel="stylesheet" type="text/css" href="css/main.css">
    <script type="text/javascript" src="js/host.js"></script>
    <script type="text/javascript" src="js/vue-2.5.16.js"></script>
    <script type="text/javascript" src="js/axios-0.18.0.min.js"></script>
</head>
<body>
    <div id="app" v-cloak>
	<div class="header_con">
        <div class="header">
            <div class="welcome fl">欢迎来到阿尔法商城!</div>
            <div class="fr">
                <div v-if="username" class="login_btn fl">
                    欢迎您:<em>username</em>
                    <span>|</span>
                    <a @click="logoutfunc">退出</a>
                </div>
                <div v-else class="login_btn fl">
                    <a href="login.html">登录</a>
                    <span>|</span>
                    <a href="register.html">注册</a>
                </div>
                <div class="user_link fl">
                    <span>|</span>
                    <a href="user_center_info.html">用户中心</a>
                    <span>|</span>
                    <a href="cart.html">我的购物车</a>
                    <span>|</span>
                    <a href="user_center_order.html">我的订单</a>
                </div>
            </div>
        </div>
	</div>

	<div class="search_bar clearfix">

以上是关于开源web框架django知识总结(二十一)的主要内容,如果未能解决你的问题,请参考以下文章

开源web框架django知识总结(二十一)

开源web框架django知识总结(二十)

开源web框架django知识总结(二十)

开源web框架django知识总结(二十)

开源web框架django知识总结(二十二)

开源web框架django知识总结(二十二)