72.简单的淘宝授权系统

该项目用到了Bootstrap样式,需要提前下载Bootstrap文件,放置在static文件夹中

 static  

  bootstrap-3.4.1-dist

    css

      bootstrap.min.css

    fonts

      所有文件

    js

      bootstrap.min.js

  css

    login-css

  dist

    sweetalert.css

    sweetalert.js

 

1.settings.py

"""
Django settings for tb project.

Generated by 'django-admin startproject' using Django 3.2.5.

For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-bbnhl5s*h&+6dlos+j=np+ul4k*c_ykrfsf(-msb56up@b!phc'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'tb.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates']
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'tb.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'tb',
        'USER': 'root',
        'PASSWORD': '123',
        'HOST': '127.0.0.1',
        'PORT': 3306,
        'CHARSET': 'utf8'
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
import os
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR,'static'),
)

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

 

2.urls.py

2.urls.py

"""tb URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, re_path
from app01 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    # 管理员登陆功能
    re_path(r'login/',views.login),
    # 首页
    re_path(r'^$', views.home, name='home'),
    # 经销商列表
    re_path(r'agency/list/' ,views.agency_list, name='agency_list'),
    # 添加经销商
    re_path(r'agency/add/' ,views.agency_add, name='agency_add'),
    # 编辑经销商
    re_path(r'agency/edit/(?P<edit_id>\d+)', views.agency_edit, name = 'agency_edit'),
    # 删除经销商
    re_path(r'agency/delete/', views.agency_delete, name='agency_delete'),
    # 系统设置
    re_path(r'system/setting/', views.system_setting, name='system_setting'),
    # 新增折扣
    re_path(r'level/add/', views.level_add, name='level_add'),
    # 编辑折扣
    re_path(r'level/edit/(?P<edit_id>\d+)', views.level_edit, name='level_edit'),
    # 删除折扣
    re_path(r'level/delete/', views.level_delete, name='level_delete'),
    # 新增平台
    re_path(r'channel/add/', views.channel_add, name='channel_add'),
    # 编辑平台
    re_path(r'channel/edit/(?P<edit_id>\d+)', views.channel_edit, name='channel_edit'),
    # 删除平台
    re_path(r'channel/delete/', views.channel_delete, name='channel_delete'),
    # 新增部门
    re_path(r'department/add/', views.department_add, name='department_add'),
    # 编辑部门
    re_path(r'department/edit/(?P<edit_id>\d+)', views.department_edit, name='department_edit'),
    # 删除部门
    re_path(r'department/delete/', views.department_delete, name='department_delete'),
]

2.urls.py

"""tb URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, re_path
from app01 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    # 管理员登陆功能
    re_path(r'login/',views.login),
    # 首页
    re_path(r'^$', views.home, name='home'),
    # 经销商列表
    re_path(r'agency/list/' ,views.agency_list, name='agency_list'),
    # 添加经销商
    re_path(r'agency/add/' ,views.agency_add, name='agency_add'),
    # 编辑经销商
    re_path(r'agency/edit/(?P<edit_id>\d+)', views.agency_edit, name = 'agency_edit'),
    # 删除经销商
    re_path(r'agency/delete/', views.agency_delete, name='agency_delete'),
    # 系统设置
    re_path(r'system/setting/', views.system_setting, name='system_setting'),
    # 新增折扣
    re_path(r'level/add/', views.level_add, name='level_add'),
    # 编辑折扣
    re_path(r'level/edit/(?P<edit_id>\d+)', views.level_edit, name='level_edit'),
    # 删除折扣
    re_path(r'level/delete/', views.level_delete, name='level_delete'),
    # 新增平台
    re_path(r'channel/add/', views.channel_add, name='channel_add'),
    # 编辑平台
    re_path(r'channel/edit/(?P<edit_id>\d+)', views.channel_edit, name='channel_edit'),
    # 删除平台
    re_path(r'channel/delete/', views.channel_delete, name='channel_delete'),
    # 新增部门
    re_path(r'department/add/', views.department_add, name='department_add'),
    # 编辑部门
    re_path(r'department/edit/(?P<edit_id>\d+)', views.department_edit, name='department_edit'),
    # 删除部门
    re_path(r'department/delete/', views.department_delete, name='department_delete'),
]

 

3.models.py

from django.db import models

# Create your models here.

class UserInfo(models.Model):
    agencyName = models.CharField(verbose_name='经销商姓名', max_length=32)
    agencyPhone = models.BigIntegerField(verbose_name='手机号')
    authorizationCode = models.CharField(verbose_name='授权码', max_length= 32)
    shopname = models.CharField(verbose_name='店铺名', max_length=32)
    shopId = models.CharField(verbose_name='店铺id', max_length=32)
    shopnet = models.CharField(verbose_name='店铺网址', max_length=255,default='http://www.baidu.com')
    salesman = models.CharField(verbose_name='业务员', max_length=32)
    supplierName = models.CharField(verbose_name='供货商姓名', max_length=32)
    supplierWechat = models.CharField(verbose_name='供货商微信号', max_length=64)
    start_date = models.DateField(verbose_name='开始日期', auto_now_add=True)
    end_date = models.DateField(verbose_name='结束日期')
    status = models.CharField(verbose_name='状态',max_length=16,default='1')

    agencyIntroduce = models.TextField(verbose_name='经销商简介',null=True)
    agencyProfession = models.CharField(verbose_name='职业',max_length=32,null=True)
    agencyCompany = models.CharField(verbose_name='工作单位',max_length=32,null=True)
    agencyBirthday = models.DateField(verbose_name='生日',null=True)
    agencyPostcode= models.CharField(verbose_name='职业',max_length=32,null=True)
    agencyAddr = models.CharField(verbose_name='职业', max_length=256,null=True)

    # 外键字段
    department = models.ForeignKey(to='Department',on_delete=models.CASCADE)
    channel = models.ForeignKey(to='ShopType',on_delete=models.CASCADE)
    level = models.ForeignKey(to='AgencyLevel',on_delete=models.CASCADE)


class Department(models.Model):
    name = models.CharField(verbose_name='部门', max_length=32)


class ShopType(models.Model):
    name = models.CharField(verbose_name='店铺名称', max_length=32)

class AgencyLevel(models.Model):
    levelname = models.CharField(verbose_name='折扣', max_length=32)

 

 

4.views.py

from django.shortcuts import render,redirect
from app01 import models
from django.contrib import auth
from mylogging import Logger
from django.http import JsonResponse

# Create your views here.

logger1 = Logger()
logger = logger1.load_logger(__name__)

# 登陆功能
def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user_obj = auth.authenticate(username=username,password=password)
        # 判断当前用户是否存在
        if user_obj:
            # 保存用户状态
            auth.login(request,user_obj)
            return redirect('/agency_list/')
    return render(request, 'login.html')

# 首页
def home(request):
    return render(request, 'home.html')


# 经销商列表
def agency_list(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    page_name = '经销商列表'
    # 店铺类型
    shoptype_jqueryset = models.ShopType.objects.all()
    # 部门
    department_jqueryset = models.Department.objects.all()
    # 等级表
    level_jqueryset = models.AgencyLevel.objects.all()

    user_jqueryset = models.UserInfo.objects
    agency_name = request.GET.get('agency_name')
    if not agency_name: agency_name = ''
    agency_authcode = request.GET.get('agency_authcode')
    if not agency_authcode: agency_authcode = ''
    agency_phone = request.GET.get('agency_phone')
    if not agency_phone: agency_phone=''
    shopname = request.GET.get('shopname')
    if not shopname: shopname = ''
    shopid = request.GET.get('shopid')
    if not shopid: shopid = ''
    salesman = request.GET.get('salesman')
    if not salesman: salesman = ''
    agencylevel = request.GET.get('agencylevel')
    if agencylevel == '0': agencylevel=None
    department = request.GET.get('department')
    if department == '0': department = None
    suppliername = request.GET.get('suppliername')
    if not suppliername: suppliername = ''
    supplierwechat = request.GET.get('supplierwechat')
    if not supplierwechat: supplierwechat = ''
    status = request.GET.get('status')
    if status == '3': status = None
    logger.info('状态:%s' %status)
    url = ''
    if agency_name:
        user_jqueryset = user_jqueryset.filter(agencyName__contains=agency_name)
        url += 'agency_name=%s' %agency_name
    if agency_authcode:
        user_jqueryset = user_jqueryset.filter(authorizationCode=agency_authcode)
        url += '&user_jqueryset=%s' % user_jqueryset
    if agency_phone:
        user_jqueryset = user_jqueryset.filter(agencyPhone=agency_phone)
        url += '&agency_phone=%s' % agency_phone
    if shopname:
        user_jqueryset = user_jqueryset.filter(shopname=shopname)
        url += '&shopname=%s' % shopname
    if shopid:
        user_jqueryset = user_jqueryset.filter(shopId=shopid)
        url += '&shopid=%s' % shopid
    if salesman:
        user_jqueryset = user_jqueryset.filter(salesman=salesman)
        url += '&salesman=%s' % salesman
    if agencylevel:
        user_jqueryset = user_jqueryset.filter(level_id=agencylevel)
        url += '&agencylevel=%s' % agencylevel
    if department:
        user_jqueryset = user_jqueryset.filter(department_id=department)
        url += '&department=%s' % department
    if suppliername:
        user_jqueryset = user_jqueryset.filter(supplierName=suppliername)
        url += '&suppliername=%s' % suppliername
    if supplierwechat:
        user_jqueryset = user_jqueryset.filter(supplierWechat=supplierwechat)
        url += '&supplierwechat=%s' % supplierwechat
    if status:
        user_jqueryset = user_jqueryset.filter(status=status)
        url += '&status=%s' % status
    user_jqueryset = user_jqueryset.all()
    all_count = user_jqueryset.count()
    print(all_count)
    current_page = request.GET.get('page', 1)
    print(current_page)
    # 1.传值生成对象
    page_obj = Pagination(current_page=current_page, all_count=all_count,url=url)
    print(page_obj)
    # 2.直接对总数据进行切片操作
    page_queryset = user_jqueryset[page_obj.start:page_obj.end]
    print(page_queryset)
    print(page_obj.start, page_obj.end)
    return render(request, 'agency_list.html', locals())

    # if request.method == 'POST':
    #     user_jqueryset = models.UserInfo.objects
    #     agency_name = request.POST.get('agency_name')
    #     agency_authcode = request.POST.get('agency_authcode')
    #     agency_phone = request.POST.get('agency_phone')
    #     shopname = request.POST.get('shopname')
    #     shopid = request.POST.get('shopid')
    #     salesman = request.POST.get('salesman')
    #     agencylevel = request.POST.get('agencylevel')
    #     department = request.POST.get('department')
    #     suppliername = request.POST.get('suppliername')
    #     supplierwechat = request.POST.get('supplierwechat')
    #     if agency_name:
    #         user_jqueryset = user_jqueryset.filter(agencyName__contains=agency_name)
    #     if agency_authcode:
    #         user_jqueryset = user_jqueryset.filter(authorizationCode=agency_authcode)
    #     if agency_phone:
    #         user_jqueryset = user_jqueryset.filter(agencyPhone=agency_phone)
    #     if shopname:
    #         user_jqueryset = user_jqueryset.filter(shopname=shopname)
    #     if shopid:
    #         user_jqueryset = user_jqueryset.filter(shopId=shopid)
    #     if salesman:
    #         user_jqueryset = user_jqueryset.filter(salesman=salesman)
    #     if agencylevel != '0':
    #         user_jqueryset = user_jqueryset.filter(level_id=agencylevel)
    #     if department != '0':
    #         user_jqueryset = user_jqueryset.filter(department_id=department)
    #     if suppliername:
    #         user_jqueryset = user_jqueryset.filter(supplierName=suppliername)
    #     if supplierwechat:
    #         user_jqueryset = user_jqueryset.filter(supplierWechat=supplierwechat)
    #     user_jqueryset=user_jqueryset.all()
    #     all_count = user_jqueryset.count()
    #     print(all_count)
    #     current_page = request.GET.get('page', 1)
    #     print(current_page)
    #     # 1.传值生成对象
    #     page_obj = Pagination(current_page=current_page, all_count=all_count)
    #     print(page_obj)
    #     # 2.直接对总数据进行切片操作
    #     page_queryset = user_jqueryset[page_obj.start:page_obj.end]
    #     print(page_queryset)
    #     print(page_obj.start,page_obj.end)
    #     return render(request,'agency_list.html',locals())


# 添加经销商
def agency_add(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    page_name = '添加经销商'
    # back_dic = {
    #     'authorizationCode':'',
    #     'shoptype_id':'',
    #     'agencylevel_id':'',
    #     'shop_name':'',
    #     'shop_id':'',
    #     'shop_net':'',
    #     'agency_name':'',
    #     'agency_phone':'',
    #     'supplier_name':'',
    #     'supplier_wechat':'',
    #     'start_date':'',
    #     'end_date':'',
    #     'department_id':''
    # }
    if request.method == 'POST':
        authorizationCode = request.POST.get('authorizationCode')
        # if not authorizationCode:back_dic['authorizationCode']='授权编码不能为空'
        shoptype_id = request.POST.get('shoptype')
        # if not shoptype_id: back_dic['shoptype_id'] = '店铺类型不能为空'
        agencylevel_id = request.POST.get('agencylevel')
        # if not agencylevel_id: back_dic['agencylevel_id'] = '经销商等级不能为空'
        shop_name = request.POST.get('shopname')
        # if not shop_name: back_dic['shop_name'] = '店铺名不能为空'
        shop_id = request.POST.get("shopid")
        # if not shop_id: back_dic['shop_id'] = '店铺id不能为空'
        shop_net = request.POST.get('shopnet')
        # if not shop_net: back_dic['shop_net'] = '店铺网址不能为空'
        agency_name = request.POST.get('agencyname')
        # if not agency_name: back_dic['agency_name'] = '经销商姓名不能为空'
        agency_phone = request.POST.get('agencyphone')
        # if not agency_phone: back_dic['agency_phone'] = '经销商手机号不能为空'
        supplier_name = request.POST.get('suppliername')
        # if not supplier_name: back_dic['supplier_name'] = '上家姓名不能为空'
        supplier_wechat = request.POST.get('supplierwechat')
        # if not supplier_wechat: back_dic['supplier_wechat'] = '上家微信号不能为空'
        salesman = request.POST.get('salesman')
        # if not salesman: back_dic['salesman'] = '业务员不能为空'
        department_id = request.POST.get('department')
        # if not department_id: back_dic['department_id'] = '部门不能为空'
        start_date = request.POST.get('start_date')
        # if not start_date: back_dic['start_date'] = '开始日期不能为空'
        end_date = request.POST.get('end_date')
        # if not end_date: back_dic['end_date'] = '结束日期不能为空'
        status = request.POST.get('status')
        agency_introduce = request.POST.get('agencyintroduce')
        agency_profession = request.POST.get('agencyprofession')
        agency_company = request.POST.get('agencycompany')
        agency_birthday = request.POST.get('agencybirthday')
        if agency_birthday == '':
            agency_birthday = None
        # print(1111)
        # print(agency_birthday)
        agency_postcode = request.POST.get('agencypostcode')
        agency_addr = request.POST.get('agencyaddr')
        # 添加数据到userInfo表中
        try:
            user_obj = models.UserInfo.objects.create(
                authorizationCode=authorizationCode,
                channel_id=shoptype_id,
                level_id=agencylevel_id,
                shopname=shop_name,
                shopId=shop_id,
                shopnet=shop_net,
                agencyName=agency_name,
                agencyPhone=agency_phone,
                supplierName=supplier_name,
                supplierWechat=supplier_wechat,
                salesman=salesman,
                department_id=department_id,
                start_date=start_date,
                end_date=end_date,
                status=status,
                agencyIntroduce=agency_introduce,
                agencyProfession=agency_profession,
                agencyCompany=agency_company,
                agencyBirthday=agency_birthday,
                agencyPostcode=agency_postcode,
                agencyAddr=agency_addr
            )
        except Exception:
            errors = '授权码不能重复,请返回重新修改'
        # 跳转到经销商列表页面
        return redirect('agency_list')
    # 店铺类型
    shoptype_jqueryset = models.ShopType.objects.all()
    # 部门
    department_jqueryset = models.Department.objects.all()
    # 等级表
    level_jqueryset = models.AgencyLevel.objects.all()
    return render(request, 'agency_add.html', locals())


# 编辑经销商
def agency_edit(request, edit_id):
    if not request.user.is_authenticated:
        return redirect('/login/')
    page_name = '编辑经销商'
    # 获取需要编辑的经销商数据
    edit_obj = models.UserInfo.objects.filter(pk=edit_id).first()
    # 获取前端提交的数据
    if request.method == 'POST':
        authorizationCode = request.POST.get('authorizationCode')
        shoptype_id = request.POST.get('shoptype')
        agencylevel_id = request.POST.get('agencylevel')
        shop_name = request.POST.get('shopname')
        shop_id = request.POST.get("shopid")
        shop_net = request.POST.get('shopnet')
        agency_name = request.POST.get('agencyname')
        agency_phone = request.POST.get('agencyphone')
        supplier_name = request.POST.get('suppliername')
        supplier_wechat = request.POST.get('supplierwechat')
        salesman = request.POST.get('salesman')
        department_id = request.POST.get('department')
        start_date = request.POST.get('start_date')
        end_date = request.POST.get('end_date')
        status = request.POST.get('status')
        agency_introduce = request.POST.get('agencyintroduce')
        agency_profession = request.POST.get('agencyprofession')
        agency_company = request.POST.get('agencycompany')
        agency_birthday = request.POST.get('agencybirthday')
        if agency_birthday == '':
            agency_birthday = None
        agency_postcode = request.POST.get('agencypostcode')
        agency_addr = request.POST.get('agencyaddr')
        # 添加数据到userInfo表中
        models.UserInfo.objects.filter(pk=edit_id).update(
            authorizationCode=authorizationCode,
            channel_id=shoptype_id,
            level_id=agencylevel_id,
            shopname=shop_name,
            shopId=shop_id,
            shopnet=shop_net,
            agencyName=agency_name,
            agencyPhone=agency_phone,
            supplierName=supplier_name,
            supplierWechat=supplier_wechat,
            salesman=salesman,
            department_id=department_id,
            start_date=start_date,
            end_date=end_date,
            status=status,
            agencyIntroduce=agency_introduce,
            agencyProfession=agency_profession,
            agencyCompany=agency_company,
            agencyBirthday=agency_birthday,
            agencyPostcode=agency_postcode,
            agencyAddr=agency_addr
        )
        # 跳转到经销商列表页面
        return redirect('agency_list')
    # 店铺类型
    shoptype_jqueryset = models.ShopType.objects.all()
    # 部门
    department_jqueryset = models.Department.objects.all()
    # 等级表
    level_jqueryset = models.AgencyLevel.objects.all()
    return render(request, 'agency_edit.html', locals())


# 删除经销商
def agency_delete(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    """
    前后端在用ajax进行交互的时候,后端通常给ajax的回调函数返回一个字典格式的数据
    :param request:
    :return:
    """
    if request.is_ajax():
        if request.method == 'POST':
            back_dict = {"code": 1000, "msg": ''}
            # time.sleep(3)  # 模拟操作数据的延迟
            delete_id = request.POST.get('delete_id')
            logger.info('这是删除的id:%s' %delete_id)
            # print(11111)
            # print(delete_id)
            models.UserInfo.objects.filter(pk=delete_id).delete()
            # 需要告诉前端,我们已经删除了数据
            # back_dict['msg'] = '数据已经删除了,你赶紧跑路!'
            return JsonResponse(back_dict)


# 分页器
from utils.mypage import *
def ab_bulk(request):
    user_queryset = models.UserInfo.objects.all()
    all_count = user_queryset.count()
    current_page = request.GET.get('page', 1)
    # 1.传值生成对象
    page_obj = Pagination(current_page=current_page, all_count=all_count)

    # 2.直接对总数据进行切片操作
    page_queryset = user_queryset[page_obj.start:page_obj.end]

    # 3.将page_queryset传递到页面,替换book_queryset
    return render(request, 'agency_list.html', locals())

# 系统设置
def system_setting(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    page_name = '系统设置'
    # 店铺类型
    shoptype_jqueryset = models.ShopType.objects.all()
    # 部门
    department_jqueryset = models.Department.objects.all()
    # 等级表
    level_jqueryset = models.AgencyLevel.objects.all()
    return render(request, 'system_setting.html', locals())


# 新增折扣
def level_add(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    page_name = '新增折扣'
    if request.method == 'POST':
        level = request.POST.get('level')
        models.AgencyLevel.objects.create(
            levelname=level
        )
        return redirect('system_setting')
    return render(request, 'level_add.html', locals())


# 编辑折扣
def level_edit(request, edit_id):
    if not request.user.is_authenticated:
        return redirect('/login/')
    page_name = '编辑折扣'
    edit_obj = models.AgencyLevel.objects.filter(pk=edit_id).first()
    if request.method == 'POST':
        level_name = request.POST.get('level')
        models.AgencyLevel.objects.filter(pk=edit_id).update(
            levelname = level_name
        )
        return redirect('system_setting')
    return render(request, 'level_edit.html', locals())


# 删除折扣
def level_delete(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    if request.is_ajax():
        if request.method == 'POST':
            back_dict = {"code": 1000, "msg": ''}
            # time.sleep(3)  # 模拟操作数据的延迟
            delete_id = request.POST.get('delete_id')
            logger.info('这是删除的id:%s' %delete_id)
            # print(11111)
            # print(delete_id)
            models.AgencyLevel.objects.filter(pk=delete_id).delete()
            # 需要告诉前端,我们已经删除了数据
            # back_dict['msg'] = '数据已经删除了,你赶紧跑路!'
            return JsonResponse(back_dict)


# 新增平台
def channel_add(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    page_name = '新增平台'
    if request.method == 'POST':
        channel = request.POST.get('channel')
        models.ShopType.objects.create(
            name=channel
        )
        return redirect('system_setting')
    return render(request, 'channel_add.html', locals())


# 编辑平台
def channel_edit(request, edit_id):
    if not request.user.is_authenticated:
        return redirect('/login/')
    page_name = '编辑平台'
    edit_obj = models.ShopType.objects.filter(pk=edit_id).first()
    if request.method == 'POST':
        channel = request.POST.get('channel')
        models.ShopType.objects.filter(pk=edit_id).update(
            name=channel
        )
        return redirect('system_setting')
    return render(request, 'channel_edit.html', locals())


# 删除平台
def channel_delete(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    if request.is_ajax():
        if request.method == 'POST':
            back_dict = {"code": 1000, "msg": ''}
            # time.sleep(3)  # 模拟操作数据的延迟
            delete_id = request.POST.get('delete_id')
            logger.info('这是删除的id:%s' %delete_id)
            # print(11111)
            # print(delete_id)
            models.ShopType.objects.filter(pk=delete_id).delete()
            # 需要告诉前端,我们已经删除了数据
            # back_dict['msg'] = '数据已经删除了,你赶紧跑路!'
            return JsonResponse(back_dict)


# 新增部门
def department_add(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    page_name = '新增部门'
    if request.method == 'POST':
        department_name = request.POST.get('department')
        models.Department.objects.create(
            name=department_name
        )
        return redirect('system_setting')
    return render(request, 'department_add.html', locals())


# 编辑部门
def department_edit(request, edit_id):
    if not request.user.is_authenticated:
        return redirect('/login/')
    page_name = '编辑部门'
    edit_obj = models.Department.objects.filter(pk=edit_id).first()
    if request.method == 'POST':
        department = request.POST.get('department')
        models.Department.objects.filter(pk=edit_id).update(
            name=department
        )
        return redirect('system_setting')
    return render(request, 'department_edit.html', locals())


# 删除部门
def department_delete(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    if request.is_ajax():
        if request.method == 'POST':
            back_dict = {"code": 1000, "msg": ''}
            # time.sleep(3)  # 模拟操作数据的延迟
            delete_id = request.POST.get('delete_id')
            logger.info('这是删除的id:%s' %delete_id)
            # print(11111)
            # print(delete_id)
            models.Department.objects.filter(pk=delete_id).delete()
            # 需要告诉前端,我们已经删除了数据
            # back_dict['msg'] = '数据已经删除了,你赶紧跑路!'
            return JsonResponse(back_dict)

 

5.agency_add.html

{% extends 'home.html' %}

{% block content %}
    <h1 class="text-center">添加经销商</h1>

    <div class="row">
        <div class="col-md-10 col-md-offset-1">
            {{ errors }}
            <form action="" method="post">
            {% csrf_token %}
                <p>经销商编号:
                    <input type="text" name="authorizationCode" style="margin-left: 35px" required>

                </p>
                <p>店铺类型:
                    <select name="shoptype" id="" style="margin-left: 50px">
                        {% for shoptype_obj in shoptype_jqueryset %}
                            <option value="{{ shoptype_obj.pk }}">{{ shoptype_obj.name }}</option>
                        {% endfor %}
                    </select>
                </p>
                <p>经销商等级:
                    <select name="agencylevel" id="" style="margin-left: 35px">
                        {% for level_obj in level_jqueryset %}
                            <option value="{{ level_obj.pk }}">{{ level_obj.levelname }}</option>
                        {% endfor %}
                    </select>
                </p>
                <p>店铺名:
                    <input type="text" name="shopname" style="margin-left: 62px" required>
                </p>
                <p>店铺ID:
                    <input type="text" name="shopid" style="margin-left: 62px" required>
                </p>
                <p>店铺网址:
                    <input type="text" name="shopnet" style="margin-left: 49px" required>
                </p>
                <p>经销商姓名:
                    <input type="text" name="agencyname" style="margin-left: 35px" required>
                </p>
                <p>经销商手机:
                    <input type="text" name="agencyphone" style="margin-left: 35px" required>
                </p>
                <p>上家经销商姓名:
                    <input type="text" name="suppliername" style="margin-left: 7px" required>
                </p>
                <p>上家经销商微信:
                    <input type="text" name="supplierwechat" style="margin-left: 7px" required>
                </p>
                <p>业务员:
                    <input type="text" name="salesman" style="margin-left: 62px" required>
                </p>
                <p>所属部门:
                    <select name="department" id="" style="margin-left: 49px">
                        {% for department_obj in department_jqueryset %}
                            <option value="{{ department_obj.pk }}">{{ department_obj.name }}</option>
                        {% endfor %}
                    </select>
                </p>
                <p>开始经销商日期:
                    <input type="date" name="start_date" style="margin-left: 7px" required>
                </p>
                <p>结束销商商日期:
                    <input type="date" name="end_date" style="margin-left: 7px" required>
                </p>
                <p>经销商状态:
                    <select name="status" id="">
                        <option value="1" selected>正常</option>
                        <option value="0">拉黑</option>
                    </select>
                </p>
                <h3 class="text-left">以下内容项选填写</h3>
                <p>经销商介绍:
                    <input type="text" name="agencyintroduce">
                </p>
                <p>经销商职业:
                    <input type="text" name="agencyprofession">
                </p>
                <p>经销商单位:
                    <input type="text" name="agencycompany">
                </p>
                <p>经销商生日:
                    <input type="date" name="agencybirthday">
                </p>
                <p>经销商邮编:
                    <input type="text" name="agencypostcode">
                </p>
                <p>经销商地址:
                    <input type="text" name="agencyaddr">
                </p>
                <input type="submit" value="添加" class="btn btn-block btn-info">
            </form>
        </div>
    </div>

{% endblock %}

 

6.agency_edit.html

{% extends 'home.html' %}

{% block content %}
    <h1 class="text-center">编辑经销商</h1>
    {% csrf_token %}
    <div class="row">
        <div class="col-md-10 col-md-offset-1">
            <form action="" method="post">
            {% csrf_token %}
                <p>经销商编号:
                    <input type="text" name="authorizationCode" value="{{ edit_obj.authorizationCode }}" style="margin-left: 35px">
                </p>
                <p>店铺类型:
                    <select name="shoptype" id=""  style="margin-left: 50px">
                        {% for shoptype_obj in shoptype_jqueryset %}
                            {% if edit_obj.channel == shoptype_obj %}
                                <option value="{{ shoptype_obj.pk }}" selected>{{ shoptype_obj.name }}</option>
                            {% else %}
                                <option value="{{ shoptype_obj.pk }}">{{ shoptype_obj.name }}</option>
                            {% endif %}
                        {% endfor %}
                    </select>
                </p>
                <p>经销商等级:
                    <select name="agencylevel" id="" style="margin-left: 35px">
                        {% for level_obj in level_jqueryset %}
                            {% if edit_obj.level == level_obj %}
                                <option value="{{ level_obj.pk }}" selected>{{ level_obj.levelname }}</option>
                            {% else %}
                                <option value="{{ level_obj.pk }}">{{ level_obj.levelname }}</option>
                            {% endif %}
                        {% endfor %}
                    </select>
                </p>
                <p>店铺名:
                    <input type="text" name="shopname" value="{{ edit_obj.shopname }}" style="margin-left: 62px">
                </p>
                <p>店铺ID:
                    <input type="text" name="shopid" value="{{ edit_obj.shopId }}" style="margin-left: 62px">
                </p>
                <p>店铺网址:
                    <input type="text" name="shopnet" value="{{ edit_obj.shopnet }}" style="margin-left: 49px">
                </p>
                <p>经销商姓名:
                    <input type="text" name="agencyname" value="{{ edit_obj.agencyName }}" style="margin-left: 35px">
                </p>
                <p>经销商手机:
                    <input type="text" name="agencyphone" value="{{ edit_obj.agencyPhone }}" style="margin-left: 35px">
                </p>
                <p>上家经销商姓名:
                    <input type="text" name="suppliername" value="{{ edit_obj.supplierName }}" style="margin-left: 7px">
                </p>
                <p>上家经销商微信:
                    <input type="text" name="supplierwechat" value="{{ edit_obj.supplierWechat }}" style="margin-left: 7px">
                </p>
                <p>业务员:
                    <input type="text" name="salesman" value="{{ edit_obj.salesman }}" style="margin-left: 62px">
                </p>
                <p>所属部门:
                    <select name="department" id="" style="margin-left: 49px">
                        {% for department_obj in department_jqueryset %}
                            {% if edit_obj.department == department_obj %}
                                <option value="{{ department_obj.pk }}" selected>{{ department_obj.name }}</option>
                            {% else %}
                                <option value="{{ department_obj.pk }}">{{ department_obj.name }}</option>
                            {% endif %}

                        {% endfor %}
                    </select>
                </p>
                <p>开始经销商日期:
                    <input type="date" name="start_date"  value="{{ edit_obj.start_date|date:'Y-m-d' }}" style="margin-left: 7px">
                </p>
                <p>结束经销商日期:
                    <input type="date" name="end_date" value="{{ edit_obj.end_date|date:'Y-m-d' }}" style="margin-left: 7px">
                </p>
                <p>经销商状态:
                    <select name="status" id="">
                        <option value="1" selected>正常</option>
                        <option value="0">拉黑</option>
                    </select>
                </p>
                <h3 class="text-left">以下内容项选填写</h3>
                <p>经销商介绍:    <!--<input type="text"  value="{{ edit_obj.agencyIntroduce }}" name="agencyintroduce">-->
                </p>
                    <textarea name="agencyintroduce"  rows="10" cols="40" style="margin-left: 88px;margin-top: -30px">{{ edit_obj.agencyIntroduce }}</textarea>
                <p>经销商职业:
                    <input type="text" value="{{ edit_obj.agencyProfession }}" name="agencyprofession">
                </p>
                <p>经销商单位:
                    <input type="text" value="{{ edit_obj.agencyCompany }}" name="agencycompany">
                </p>
                <p>经销商生日:
                    <input type="date" value="{{ edit_obj.agencyBirthday|date:'Y-m-d' }}" name="agencybirthday">
                </p>
                <p>经销商邮编:
                    <input type="text" value="{{ edit_obj.agencyPostcode }}" name="agencypostcode">
                </p>
                <p>经销商地址:
                    <input type="text" value="{{ edit_obj.agencyAddr }}" name="agencyaddr">
                </p>
                <input type="submit" value="添加" class="btn btn-block btn-info">
            </form>
        </div>
    </div>

{% endblock %}

 

7.agency_list.html

{% extends 'home.html' %}
{% block css %}
    {% load static %}

{% endblock %}

{% block content %}
    <form action="">
    {% csrf_token %}
        <div class="row" style="padding: 10px 30px">
              <div class="col-lg-2" >
                <div class="input-group">
                  <input type="text" class="form-control" placeholder="姓名" name="agency_name" value="{{ agency_name }}">
                </div><!-- /input-group -->
              </div><!-- /.col-lg-6 -->
              <div class="col-lg-2">
                <div class="input-group">
                  <input type="text" class="form-control" placeholder="授权码" name="agency_authcode" value="{{ agency_authcode }}">
                </div><!-- /input-group -->
              </div><!-- /.col-lg-6 -->
                <div class="col-lg-2">
                <div class="input-group">
                  <input type="text" class="form-control" placeholder="手机号" name="agency_phone" value="{{ agency_phone }}">
                </div><!-- /input-group -->
              </div><!-- /.col-lg-6 -->
            <div class="col-lg-2">
                <div class="input-group">
                  <input type="text" class="form-control" placeholder="店铺名" name="shopname" value="{{ shopname }}">
                </div><!-- /input-group -->
              </div><!-- /.col-lg-6 -->
            <div class="col-lg-2">
                <div class="input-group">
                  <input type="text" class="form-control" placeholder="店铺id" name="shopid" value="{{ shopid }}">
                </div><!-- /input-group -->
              </div><!-- /.col-lg-6 -->
            <div class="col-lg-2">
                <div class="input-group">
                  <input type="text" class="form-control" placeholder="业务员姓名" name="salesman" value="{{ salesman }}">
                </div><!-- /input-group -->
              </div><!-- /.col-lg-6 -->
            </div><!-- /.row -->
        <div class="row" style="padding: 10px 30px">
              <div class="col-lg-2" >
                <div class="input-group">
                    <select name="agencylevel" id="" style="margin-left: 0px ;width:200px" class="form-control">
                        <option value="0" selected >--请选择折扣--</option>
                        {% for level_obj in level_jqueryset %}
                                <option value="{{ level_obj.pk }}">{{ level_obj.levelname }}</option>
                            {% endfor %}
                    </select>
                </div><!-- /input-group -->
              </div><!-- /.col-lg-6 -->
              <div class="col-lg-2">
                <div class="input-group">
                  <select name="department" id="" style="margin-left: 0px ;width:200px" class="form-control">
                     <option value="0" selected >--请选择部门--</option>
                     {% for department_obj in department_jqueryset %}
                        <option value="{{ department_obj.pk }}">{{ department_obj.name }}</option>
                     {% endfor %}
                  </select>
                </div><!-- /input-group -->
              </div><!-- /.col-lg-6 -->
                <div class="col-lg-2">
                <div class="input-group">
                  <input type="text" class="form-control" placeholder="供货商姓名" name="suppliername" value="{{ suppliername }}">
                </div><!-- /input-group -->
              </div><!-- /.col-lg-6 -->
            <div class="col-lg-2">
                <div class="input-group">
                  <input type="text" class="form-control" placeholder="供货商微信号" name="supplierwechat" value="{{ supplierwechat }}">
                </div><!-- /input-group -->
              </div><!-- /.col-lg-6 -->
            <div class="col-lg-2">
                <div class="input-group">
                  <select name="status" id="" style="margin-left: 0px ;width:200px" class="form-control">
                     <option value="3" selected >--请选择状态--</option>
                      <option value="1">正常</option>
                      <option value="0">拉黑</option>
                  </select>
                </div><!-- /input-group -->
              </div><!-- /.col-lg-6 -->
            <div class="col-lg-2">
                <div class="input-group">
                  <input type="submit" class="btn btn-primary" value="查询" id="d1">
                </div><!-- /input-group -->
              </div><!-- /.col-lg-6 -->
            </div><!-- /.row -->
    </form>

    <p>
    <a href="{% url 'agency_add' %}" class="btn btn-success" style="margin-left: 30px">添加</a>
    </p>

    <hr>
    <table class="table-striped table table-hover">
                            <thead>
                                <tr>
                                    <th>序号</th>
                                    <th>店铺授权码</th>
                                    <th>经销商渠道</th>
                                    <th>等级</th>
                                    <th>店铺名</th>
                                    <th>店铺ID</th>
                                    <th>经销商姓名</th>
                                    <th>经销商手机号</th>
                                    <th>业务员</th>
                                    <th>部门</th>
                                    <th>供货商</th>
                                    <th>供货商微信号</th>
                                    <th>是否到期</th>
                                    <th>是否拉黑</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for user_obj in page_queryset %}
                                    <tr>
                                        <td>{{ user_obj.pk }}</td>
                                        <td>{{ user_obj.authorizationCode }}</td>
                                        <td>{{ user_obj.channel.name }}</td>
                                        <td>{{ user_obj.level.levelname }}</td>
                                        <td>{{ user_obj.shopname }}</td>
                                        <td>{{ user_obj.shopId }}</td>
                                        <td>{{ user_obj.agencyName }}</td>
                                        <td>{{ user_obj.agencyPhone }}</td>
                                        <td>{{ user_obj.salesman }}</td>
                                        <td>{{ user_obj.department.name }}</td>
                                        <td>{{ user_obj.supplierName }}</td>
                                        <td>{{ user_obj.supplierWechat }}</td>
                                        <td>{{ user_obj.end_date|date:'Y-m-d' }}</td>
                                            {% if user_obj.status == '0' %}
                                                <td style="color: red">拉黑</td>
                                            {% else %}
                                                <td style="color: green">正常</td>
                                            {% endif %}
                                        <td class="text-center">
                                            <a href="{% url 'agency_edit' user_obj.pk %}" class="btn-success btn btn-xs">编辑</a>
                                            <button onclick="confirmClick({{ user_obj.pk }})" class="btn btn-danger btn-xs del">删除</button>
                                        </td>
                                    </tr>
                                {% endfor %}

                            </tbody>
                        </table>
    {#    利用自定义分页器直接显示分页器样式#}
    <div class="row text-center">{{ page_obj.page_html|safe }}</div>
{#    <script>#}
{#        $('.del').on('click',function () {#}
            {#alert(123)#}
            {#alert($(this).attr('delete_id'))#}
{#            // 先获取当前标签对象并存储起来#}
{#            let currentBtn = $(this)#}
{#            // 二次确认弹框#}
{#            swal({#}
{#              title: "你确定要删除吗?",#}
{#              text: "你可要考虑清楚哦,有可能需要提桶跑路哦!",#}
{#              type: "warning",#}
{#              showCancelButton: true,#}
{#              confirmButtonClass: "btn-danger",#}
{#              confirmButtonText: "是的,老子就要删除!",#}
{#              cancelButtonText: "算了,算了!",#}
              {#showLoaderOnConfirm: true,#}
{#              closeOnConfirm: false,#}
{#              closeOnCancel: false#}
{#            },#}
{#            function(isConfirm) {#}
{#              if (isConfirm) {#}
{#                  // 朝后短发送ajax请求删除数据之后,再弹出下面的提示框#}
{#                $.ajax({#}
{#                    // 传递主键值方式1#}
{#                    url:'/agency_delete/',  // 方式2:放在请求体中#}
{#                    type:'post',#}
{#                    data: {'delete_id':currentBtn.attr('delete_id')},#}
{#                    success:function (args) {#}
{#                        // 判断响应状态码,然后做不同的处理#}
{#                        if (args.code === 1000){#}
{#                            swal("删除了!", args.msg, "success");#}
{#                            // 1.lowb版本,直接刷新当期页面#}
{#                            window.location.reload()#}
{#                            // 2.利用DOM操作 动态刷新#}
{#                            currentBtn.parent().parent().remove()#}
{#                        }else {#}
{#                            swal("完了!", "出现了未知的错误!", "info");#}
{#                        }#}
{#                    }#}
{#                })#}
{##}
{#              } else {#}
{#                swal("怂逼", "不要说我认识你!", "error");#}
{#              }#}
{#            });#}
{#        })#}
{#    </script>#}
    <script>
        function confirmClick(id) {
            {#let currentBtn = $(this)#}
            var result = confirm("您确认要删除吗,一旦删除不可恢复");
            if(result) {
                $.ajax({
                    // 传递主键值方式1
                    url: '/agency/delete/',  // 方式2:放在请求体中
                    type: 'post',
                    data: {'delete_id': id},
                    success: function (args) {
                        // 判断响应状态码,然后做不同的处理
                        if (args.code === 1000) {
                            alert("删除了!", args.msg);
                            // 1.lowb版本,直接刷新当期页面
                            window.location.reload()
                            // 2.利用DOM操作 动态刷新
                            currentBtn.parent().parent().remove()
                        } else {
                            alert("完了!", "出现了未知的错误!");
                        }
                    }
                })
            }else {
                alert("怂逼", "不要说我认识你!");
              }
        }
    </script>
{% endblock %}

 

 

8.channel_add.html

{% extends 'home.html' %}

{% block content %}
    <h1 class="text-center">新增平台</h1>
    <div class="container">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <form action="" method="post">
                    <p >请输入平台名称:
                        <input type="text" name="channel" class="form-control">
                    </p>
                    <input type="submit" value="添加平台" class="btn btn-success">
                </form>
            </div>
        </div>
    </div>

{% endblock %}

 

 

9.channel_edit.html

{% extends 'home.html' %}

{% block content %}
    <h1 class="text-center">修改平台</h1>
    <div class="container">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <form action="" method="post">
                    <p >请输入平台名称:
                        <input type="text" name="channel" class="form-control" value="{{ edit_obj.name }}">
                    </p>
                    <input type="submit" value="修改平台" class="btn btn-success">
                </form>
            </div>
        </div>
    </div>

{% endblock %}

 

10.department_add.html

{% extends 'home.html' %}

{% block content %}
    <h1 class="text-center">新增部门</h1>
    <div class="container">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <form action="" method="post">
                    <p >请输入部门名称:
                        <input type="text" name="department" class="form-control">
                    </p>
                    <input type="submit" value="添加部门" class="btn btn-success">
                </form>
            </div>
        </div>
    </div>

{% endblock %}

 

11.department_eidt.html

{% extends 'home.html' %}

{% block content %}
    <h1 class="text-center">修改部门</h1>
    <div class="container">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <form action="" method="post">
                    <p >请输入部门名称:
                        <input type="text" name="department" class="form-control" value="{{ edit_obj.name }}">
                    </p>
                    <input type="submit" value="修改部门" class="btn btn-success">
                </form>
            </div>
        </div>
    </div>

{% endblock %}

 

 

12.home.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>淘宝授权系统</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
    {% load static %}
    <link rel="stylesheet" href="{% static 'dist/sweetalert.css' %}">
    <script src="{% static 'dist/sweetalert.js' %}"></script>
    <style>
        div.sweet-alert h2 {
            padding-top: 10px;
        }

        a:hover {
            background-color:red;
            text-decoration:none;
            }
    </style>
    {% block css %}
    
    {% endblock %}
</head>
<body>
    <nav class="navbar navbar-inverse">
      <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Brand</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
          <ul class="nav navbar-nav">
            <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
            <li><a href="#">Link</a></li>
            <li class="dropdown">
              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
              <ul class="dropdown-menu">
                <li><a href="#">Action</a></li>
                <li><a href="#">Another action</a></li>
                <li><a href="#">Something else here</a></li>
                <li role="separator" class="divider"></li>
                <li><a href="#">Separated link</a></li>
                <li role="separator" class="divider"></li>
                <li><a href="#">One more separated link</a></li>
              </ul>
            </li>
          </ul>
          <form class="navbar-form navbar-left">
            <div class="form-group">
              <input type="text" class="form-control" placeholder="Search">
            </div>
            <button type="submit" class="btn btn-default">Submit</button>
          </form>
          <ul class="nav navbar-nav navbar-right">
            <li><a href="#">Link</a></li>
            <li class="dropdown">
              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
              <ul class="dropdown-menu">
                <li><a href="#">Action</a></li>
                <li><a href="#">Another action</a></li>
                <li><a href="#">Something else here</a></li>
                <li role="separator" class="divider"></li>
                <li><a href="#">Separated link</a></li>
              </ul>
            </li>
          </ul>
        </div><!-- /.navbar-collapse -->
      </div><!-- /.container-fluid -->
    </nav>
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-2">
                <div class="list-group">
{#                  <a href="{% url 'home' %}" class="list-group-item">#}
{#                    首页#}
{#                  </a>#}
                  <a href="{% url 'agency_list' %}" class="list-group-item">经销商列表</a>
                  <a href="{% url 'agency_add' %}" class="list-group-item">新增经销商</a>
                  <a href="#" class="list-group-item">导出经销商</a>
                  <a href="{% url 'system_setting' %}" class="list-group-item">系统设置</a>
                </div>
            </div>
            <div class="col-md-10">
                <div class="panel panel-primary">

                  <div class="panel-heading">
                    <h3 class="panel-title">{{ page_name }}</h3>

                  </div>
                    <hr>
                    <div class="row">
                      <div class="panel-body">
                        {% block content %}
                            <div class="jumbotron">
                                  <h1>欢迎来到淘宝授权系统!!!</h1>
                                  <p>这是新的淘宝授权系统</p>
                                  <p><a class="btn btn-primary btn-lg" href="/login/" role="button">点此登陆系统</a></p>
                            </div>
                          {% endblock %}
                  </div>
                </div>
            </div>
        </div>
    </div>

{% block js %}

{% endblock %}
</body>
</html>

 

 

13.level_add.html

{% extends 'home.html' %}

{% block content %}
    <h1 class="text-center">新增折扣</h1>
    <div class="container">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <form action="" method="post">
                    <p >请输入折扣:
                        <input type="text" name="level" class="form-control">
                    </p>
                    <input type="submit" value="添加折扣" class="btn btn-success">
                </form>
            </div>
        </div>
    </div>

{% endblock %}

 

14.level_edit.html

{% extends 'home.html' %}

{% block content %}
    <h1 class="text-center">修改折扣</h1>
    <div class="container">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <form action="" method="post">
                    <p >请输入折扣:
                        <input type="text" name="level" class="form-control" value="{{ edit_obj.levelname }}">
                    </p>
                    <input type="submit" value="修改折扣" class="btn btn-success">
                </form>
            </div>
        </div>
    </div>

{% endblock %}

 

15.login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登陆页面</title>
    <style>
        html{
                width: 100%;
                height: 100%;
                overflow: hidden;
                /*font-style: sans-serif;*/
            }
            body{
                width: 100%;
                height: 100%;
                font-family: 'Open Sans',sans-serif;
                margin: 0;
                background-color: #204d74;
            }
            #login{
                position: absolute;
                top: 50%;
                left:50%;
                margin: -150px 0 0 -150px;
                width: 300px;
                height: 300px;
            }
            #login h1{
                color: #fff;
                text-shadow:0 0 10px;
                letter-spacing: 1px;
                text-align: center;
            }
            h1{
                font-size: 2em;
                margin: 0.67em 0;
            }
            input{
                width: 278px;
                height: 18px;
                margin-bottom: 10px;
                outline: none;
                padding: 10px;
                font-size: 13px;
                color: #fff;
                text-shadow:1px 1px 1px;
                border-top: 1px solid #312E3D;
                border-left: 1px solid #312E3D;
                border-right: 1px solid #312E3D;
                border-bottom: 1px solid #56536A;
                border-radius: 4px;
                background-color: #2D2D3F;
            }
            .but{
                width: 300px;
                min-height: 20px;
                display: block;
                background-color: #4a77d4;
                border: 1px solid #3762bc;
                color: #fff;
                padding: 9px 14px;
                font-size: 15px;
                line-height: normal;
                border-radius: 5px;
                margin: 0;
            }
    </style>
{#    {% load static %}#}
{#    <link rel="stylesheet" type="text/css" href="{% static 'css/login_css.css'  %}"/>#}
</head>
<body>
    <div id="login">
        <h1>登陆页面</h1>
        <form method="post" action="">
            {% csrf_token %}
            <input type="text" required="required" placeholder="用户名" name="username">
            <input type="password" required="required" placeholder="密码" name="password">
            <button class="but" type="submit">登录</button>
        </form>
    </div>
</body>
</html>

 

16.system_settings.html

{% extends 'home.html' %}

{% block content %}
    <div class="container">
        <div class="row">
            {#   放折扣模块         #}
            <div class="col-md-4">
                <table class="table-hover table table-striped">
                    <thead>
                        <tr>
                            <h4 class="text-center">折扣设置</h4>
                            <a href="{% url 'level_add' %}" class="btn btn-success btn-sm">新增折扣</a>
                        </tr>
                        <tr>
                            <th>序号</th>
                            <th>折扣</th>
                            <th class="text-center">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for level_obj in level_jqueryset %}
                            <tr>
                                <td>{{ forloop.counter }}</td>
                                <td>{{ level_obj.levelname }}</td>
                                <td class="text-center">
                                    <a href="{% url 'level_edit' level_obj.pk %}" class="btn btn-xs btn-primary">编辑</a>
                                    <button onclick="confirmClick_level({{ level_obj.pk }})" class="btn btn-danger btn-xs del">删除</button>
                                </td>

                            </tr>
                        {% endfor %}

                    </tbody>
                </table>
            </div>
            {# 这里是平台分类渠道 #}
            <div class="col-md-4">
                <table class="table-hover table table-striped">
                    <thead>
                        <tr>
                            <h4 class="text-center">平台设置</h4>
                            <a href="{% url 'channel_add' %}" class="btn btn-success btn-sm">新增平台</a>
                        </tr>
                        <tr>
                            <th>序号</th>
                            <th>平台名称</th>
                            <th class="text-center">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for shoptype_obj in shoptype_jqueryset %}
                            <tr>
                                <td>{{ forloop.counter }}</td>
                                <td>{{ shoptype_obj.name }}</td>
                                <td class="text-center">
                                    <a href="{% url 'channel_edit' shoptype_obj.pk %}" class="btn btn-xs btn-primary">编辑</a>
                                    <button onclick="confirmClick_channel({{ shoptype_obj.pk }})" class="btn btn-danger btn-xs del">删除</button>
                                </td>

                            </tr>
                        {% endfor %}

                    </tbody>
                </table>
            </div>
            {# 部门模块 #}
            <div class="col-md-4">
                <table class="table-hover table table-striped">
                    <thead>
                        <tr>
                            <h4 class="text-center">部门设置</h4>
                            <a href="{% url 'department_add' %}" class="btn btn-success btn-sm">新增部门</a>
                        </tr>
                        <tr>
                            <th>序号</th>
                            <th>部门名称</th>
                            <th class="text-center">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for department_obj in department_jqueryset %}
                            <tr>
                                <td>{{ forloop.counter }}</td>
                                <td>{{ department_obj.name }}</td>
                                <td class="text-center">
                                    <a href="{% url 'department_edit' department_obj.pk %}" class="btn btn-xs btn-primary">编辑</a>
                                    <button onclick="confirmClick_department({{ department_obj.pk }})" class="btn btn-danger btn-xs del">删除</button>
                                </td>

                            </tr>
                        {% endfor %}

                    </tbody>
                </table>
            </div>
        </div>
    </div>
    {#折扣删除#}
    <script>
        function confirmClick_level(id) {
            {#let currentBtn = $(this)#}
            var result = confirm("您确认要删除吗,一旦删除不可恢复");
            if(result) {

                $.ajax({
                    // 传递主键值方式1
                    url: '/level/delete/',  // 方式2:放在请求体中
                    type: 'post',
                    data: {'delete_id': id},
                    success: function (args) {
                        // 判断响应状态码,然后做不同的处理
                        if (args.code === 1000) {
                            alert("删除了!", args.msg);
                            // 1.lowb版本,直接刷新当期页面
                            window.location.reload()
                            // 2.利用DOM操作 动态刷新
                            {#currentBtn.parent().parent().remove()#}
                        } else {
                            alert("完了!", "出现了未知的错误!");
                        }
                    }
                })
            }else {
                alert("怂逼", "不要说我认识你!");
              }
        }

        function confirmClick_channel(id) {
            {#let currentBtn = $(this)#}
            var result = confirm("您确认要删除吗,一旦删除不可恢复");
            if(result) {

                $.ajax({
                    // 传递主键值方式1
                    url: '/channel/delete/',  // 方式2:放在请求体中
                    type: 'post',
                    data: {'delete_id': id},
                    success: function (args) {
                        // 判断响应状态码,然后做不同的处理
                        if (args.code === 1000) {
                            alert("删除了!", args.msg);
                            // 1.lowb版本,直接刷新当期页面
                            window.location.reload()
                            // 2.利用DOM操作 动态刷新
                            {#currentBtn.parent().parent().remove()#}
                        } else {
                            alert("完了!", "出现了未知的错误!");
                        }
                    }
                })
            }else {
                alert("怂逼", "不要说我认识你!");
              }
        }

        function confirmClick_department(id) {
            {#let currentBtn = $(this)#}
            var result = confirm("您确认要删除吗,一旦删除不可恢复");
            if(result) {

                $.ajax({
                    // 传递主键值方式1
                    url: '/department/delete/',  // 方式2:放在请求体中
                    type: 'post',
                    data: {'delete_id': id},
                    success: function (args) {
                        // 判断响应状态码,然后做不同的处理
                        if (args.code === 1000) {
                            alert("删除了!", args.msg);
                            // 1.lowb版本,直接刷新当期页面
                            window.location.reload()
                            // 2.利用DOM操作 动态刷新
                            {#currentBtn.parent().parent().remove()#}
                        } else {
                            alert("完了!", "出现了未知的错误!");
                        }
                    }
                })
            }else {
                alert("怂逼", "不要说我认识你!");
              }
        }
    </script>
{% endblock %}

 

17.utils/mypage.py

class Pagination(object):
    def __init__(self, current_page, all_count, per_page_num=15, pager_count=10,url=None):
        """
        封装分页相关数据
        :param current_page: 当前页
        :param all_count:    数据库中的数据总条数
        :param per_page_num: 每页显示的数据条数
        :param pager_count:  最多显示的页码个数
        """
        try:
            current_page = int(current_page)
        except Exception as e:
            current_page = 1

        if current_page < 1:
            current_page = 1

        self.current_page = current_page

        self.all_count = all_count
        self.per_page_num = per_page_num
        self.url = url
        # 总页码
        all_pager, tmp = divmod(all_count, per_page_num)
        if tmp:
            all_pager += 1
        self.all_pager = all_pager

        self.pager_count = pager_count
        self.pager_count_half = int((pager_count - 1) / 2)

    @property
    def start(self):
        return (self.current_page - 1) * self.per_page_num

    @property
    def end(self):
        return self.current_page * self.per_page_num

    def page_html(self):
        # 如果总页码 < 11个:
        if self.all_pager <= self.pager_count:
            pager_start = 1
            pager_end = self.all_pager + 1
        # 总页码  > 11
        else:
            # 当前页如果<=页面上最多显示11/2个页码
            if self.current_page <= self.pager_count_half:
                pager_start = 1
                pager_end = self.pager_count + 1

            # 当前页大于5
            else:
                # 页码翻到最后
                if (self.current_page + self.pager_count_half) > self.all_pager:
                    pager_end = self.all_pager + 1
                    pager_start = self.all_pager - self.pager_count + 1
                else:
                    pager_start = self.current_page - self.pager_count_half
                    pager_end = self.current_page + self.pager_count_half + 1

        page_html_list = []
        # 添加前面的nav和ul标签
        page_html_list.append('''
                    <nav aria-label='Page navigation>'
                    <ul class='pagination'>
                ''')
        first_page = '<li><a href="?%s&page=%s">首页</a></li>' % (self.url,1)
        page_html_list.append(first_page)

        if self.current_page <= 1:
            prev_page = '<li class="disabled"><a href="#">上一页</a></li>'
        else:
            prev_page = '<li><a href="?%s&page=%s">上一页</a></li>' % (self.url,self.current_page - 1,)

        page_html_list.append(prev_page)

        for i in range(pager_start, pager_end):
            if i == self.current_page:
                temp = '<li class="active"><a href="?%s&page=%s">%s</a></li>' % (self.url,i, i,)
            else:
                temp = '<li><a href="?%s&page=%s">%s</a></li>' % (self.url,i, i,)
            page_html_list.append(temp)

        if self.current_page >= self.all_pager:
            next_page = '<li class="disabled"><a href="#">下一页</a></li>'
        else:
            next_page = '<li><a href="?%s&page=%s">下一页</a></li>' % (self.url,self.current_page + 1,)
        page_html_list.append(next_page)

        last_page = '<li><a href="?%s&page=%s">尾页</a></li>' % (self.url,self.all_pager,)
        page_html_list.append(last_page)
        # 尾部添加标签
        page_html_list.append('''
                                           </nav>
                                           </ul>
                                       ''')
        return ''.join(page_html_list)

 

18.myloggin.py

# -*- coding: utf-8 -*-
# @Time : 2021/10/19 14:41
# @Author : March
# @File : settings.py
import os
import logging.config


"""
 #配置日志文件
 """
class Logger():
    logfile_dir = os.path.dirname(os.path.abspath(__file__))  # logs文件的目录
    def __init__(self):
        #日志文件不存在,创建
        if not os.path.isdir(os.path.join(Logger.logfile_dir, 'logs')):
            os.mkdir(os.path.join(Logger.logfile_dir, 'logs'))


    standard_format = '[%(asctime)s:%(levelname)s:task_id:%(name)s in %(filename)s:%(pathname)s:%(lineno)d]' \
                      '>>>:%(message)s'
    simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'

    error_format = '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'

    # log文件的全路径
    logfile_path = os.path.join(logfile_dir, 'logs', 'info.log')
    error_logfile_path = os.path.join(logfile_dir, 'logs', 'error.log')

    logging_dic = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'standard': {
                'format': standard_format
            },
            'simple': {
                'format': simple_format
            },
            'error': {
                'format': error_format
            },
        },
        'filters': {},
        # 日志的执行者
        'handlers': {
            # 打印到终端的日志
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',  # 打印到屏幕
                'formatter': 'simple'
            },
            # 打印到文件的日志,收集info及以上的日志
            'default': {
                'level': 'DEBUG',
                'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件,日志轮转
                'formatter': 'standard',
                'filename': logfile_path,  # 日志文件
                'maxBytes': 1024 * 1024 * 20,  # 日志大小 5M
                'backupCount': 15,
                'encoding': 'utf-8',  # 日志文件的编码,再也不用担心中文log乱码了
            },
            # 只保存出现错误及以上的日志
            'error': {
                'level': 'ERROR',
                'class': 'logging.FileHandler',  # 保存到文件,没有分割文件的功能
                'formatter': 'error',
                'filename': error_logfile_path,
                'encoding': 'utf-8',
            },
        },
        # 日志的生产者
        'loggers': {
            # logging.getLogger(__name__)拿到的logger配置,
            # 空的指定对象,在不指定的情况下,默认使用该对象中的handlers
            '': {
                'handlers': ['default', 'console'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
                'level': 'DEBUG',  # loggers(第一层日志级别关限制)--->handlers(第二层日志级别关卡限制)
                'propagate': False,  # 默认为True,向上(更高level的logger)传递,通常设置为False即可,否则会一份日志向上层层传递
            },
            'error': {
                'handlers': ['error', ],
                'level': 'DEBUG',
                'propagate': False,
            },
        },
    }

    #调用日志对象
    @staticmethod
    def load_logger(logger_name=''):    #传入一个日志的类型,名称为loggers中的,如果没有默认''
        logging.config.dictConfig(Logger.logging_dic)  # 导入上面定义的logging配置
        logger = logging.getLogger(logger_name)  # 生成一个log实例变量对应日志配置中的%(name)s
        return logger  #返回一个日志对象,可以直接调用




if __name__ == '__main__':
    logger1=Logger()
    logger = logger1.load_logger(__name__)
    logger.info('这个是正常日志信息')

 

20.复制项目的时候,打包处理,执行以下两行代码

pip install pipreqs
pipreqs  目录  --encoding=utf8  

生成文件:requirements.txt

Django==3.2.5
PyMySQL==1.0.2

 

posted @ 2021-11-13 16:24  五仁味儿月饼  阅读(87)  评论(0编辑  收藏  举报