第一章:前端开发基础:html
第二章:前端开发基础:CSS
第三章:前端开发基础:JavaScript
第四章:前端开发基础:jQuery
第五章:前端UI框架 Layui
Layui(流畅的UI)是一款轻量级的前端框架,专为快速开发Web界面而设计。它提供了一套简单、直观、易于使用的API,可以帮助开发者更高效地构建各种Web应用
以下是 Layui 的一些主要特点和组件:
同类产品:bootstrap、easyUI
官网
http://layui.apixx.net/index.html
django-admin startproject layui
cd layui/
mkdir static
mkdir templates
python3 manage.py startapp mylayui
# layui/setting.py增加修改
# 修改
ALLOWED_HOSTS = ['*']
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(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',
],
},
},
]
# 增加
import os
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
上边下载的layui解压后,传到static目录下
# layui/urls.py
from django.contrib import admin
from django.urls import path,re_path
from mylayui import views
urlpatterns = [
path('admin/', admin.site.urls),
re_path('^$',views.index),
]
# mylayui/views.py
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,'index.html')
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Layuititle>
head>
<body>
<p>hellop>
body>
html>
python3 manage.py runserver 0.0.0.0:8080
https://www.uimaker.com/layui/doc/index.html
把后台布局这一套代码复制到自己index,然后修改,看看效果
DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>运维管理平台title>
<link rel="stylesheet" href="/static/layui/css/layui.css">
head>
<body>
<div class="layui-layout layui-layout-admin">
<div class="layui-header layui-bg-cyan">
<div class="layui-logo layui-hide-xs layui-bg-black" style="font-size: 26px;">运维管理平台div>
<ul class="layui-nav layui-layout-left">
<li class="layui-nav-item layui-show-xs-inline-block layui-hide-sm" lay-header-event="menuLeft">
<i class="layui-icon layui-icon-spread-left">i>
li>
ul>
<ul class="layui-nav layui-layout-right">
<li class="layui-nav-item layui-hide layui-show-md-inline-block">
<a href="javascript:;">
<img src="//tva1.sinaimg.cn/crop.0.0.118.118.180/5db11ff4gw1e77d3nqrv8j203b03cweg.jpg"
class="layui-nav-img">
用户
a>
<dl class="layui-nav-child">
<dd><a href="">个人信息a>dd>
<dd><a href="">设置a>dd>
<dd><a href="">退出a>dd>
dl>
li>
<li class="layui-nav-item" lay-header-event="menuRight" lay-unselect>
<a href="javascript:;">
<i class="layui-icon layui-icon-more-vertical">i>
a>
li>
ul>
div>
<div class="layui-side layui-bg-black">
<div class="layui-side-scroll layui-bg-cyan">
<ul class="layui-nav layui-nav-tree layui-bg-cyan" lay-filter="test">
<li class="layui-nav-item layui-nav-itemed">
<a class="" href="javascript:;"><i class="layui-icon layui-icon-face-smile">i> 其他系统a>
<dl class="layui-nav-child">
<dd><a href="javascript:;">OAa>dd>
<dd><a href="javascript:;">人事a>dd>
<dd><a href="javascript:;">考核a>dd>
<dd><a href="">the linksa>dd>
dl>
li>
<li class="layui-nav-item">
<a href="javascript:;">自动化a>
<dl class="layui-nav-child">
<dd><a href="javascript:;">CIa>dd>
<dd><a href="javascript:;">CDa>dd>
<dd><a href="">超链接a>dd>
dl>
li>
<li class="layui-nav-item"><a href="javascript:;">k8sa>li>
<li class="layui-nav-item"><a href="">邮箱系统a>li>
ul>
div>
div>
<div class="layui-body">
<div style="padding: 15px;">内容主体区域。记得修改 layui.css 和 js 的路径div>
div>
<div class="layui-footer">
底部固定区域www.test.com
div>
div>
<script src="/static/layui/layui.js">script>
<script>
//JS
layui.use(['element', 'layer', 'util'], function () {
var element = layui.element
, layer = layui.layer
, util = layui.util
, $ = layui.$;
//头部事件
util.event('lay-header-event', {
//左侧菜单事件
menuLeft: function (othis) {
layer.msg('展开左侧菜单的操作', { icon: 0 });
}
, menuRight: function () {
layer.open({
type: 1
, content: '处理右侧面板的操作'
, area: ['260px', '100%']
, offset: 'rt' //右上角
, anim: 5
, shadeClose: true
});
}
});
});
script>
body>
html>
红框里边的都改动过
1. | 采用 layui-row 来定义行,如: |
2. | 采用类似 layui-col-md* 这样的预设类来定义一组列(column),且放在行(row)内。其中:
|
3. | 列可以同时出现最多四种不同的组合,分别是:xs(超小屏幕,如手机)、sm(小屏幕,如平板)、md(桌面中等屏幕)、lg(桌面大型屏幕),以呈现更加动态灵活的布局。 |
4. | 可对列追加类似 layui-col-space5、 layui-col-md-offset3 这样的预设类来定义列的间距和偏移。 |
5. | 最后,在列(column)元素中放入你自己的任意元素填充内容,完成布局! |
DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>运维管理平台title>
<link rel="stylesheet" href="/static/layui/css/layui.css">
head>
<body>
<div class="layui-layout layui-layout-admin">
<div class="layui-header layui-bg-cyan">
<div class="layui-logo layui-hide-xs layui-bg-black" style="font-size: 26px;">运维管理平台div>
<ul class="layui-nav layui-layout-left">
<li class="layui-nav-item layui-show-xs-inline-block layui-hide-sm" lay-header-event="menuLeft">
<i class="layui-icon layui-icon-spread-left">i>
li>
ul>
<ul class="layui-nav layui-layout-right">
<li class="layui-nav-item layui-hide layui-show-md-inline-block">
<a href="javascript:;">
<img src="//tva1.sinaimg.cn/crop.0.0.118.118.180/5db11ff4gw1e77d3nqrv8j203b03cweg.jpg"
class="layui-nav-img">
用户
a>
<dl class="layui-nav-child">
<dd><a href="">个人信息a>dd>
<dd><a href="">设置a>dd>
<dd><a href="">退出a>dd>
dl>
li>
<li class="layui-nav-item" lay-header-event="menuRight" lay-unselect>
<a href="javascript:;">
<i class="layui-icon layui-icon-more-vertical">i>
a>
li>
ul>
div>
<div class="layui-side layui-bg-black">
<div class="layui-side-scroll layui-bg-cyan">
<ul class="layui-nav layui-nav-tree layui-bg-cyan" lay-filter="test">
<li class="layui-nav-item layui-nav-itemed">
<a class="" href="javascript:;"><i
class="layui-icon layui-icon-face-smile">i> 其他系统a>
<dl class="layui-nav-child">
<dd><a href="javascript:;">OAa>dd>
<dd><a href="javascript:;">人事a>dd>
<dd><a href="javascript:;">考核a>dd>
<dd><a href="">the linksa>dd>
dl>
li>
<li class="layui-nav-item">
<a href="javascript:;">自动化a>
<dl class="layui-nav-child">
<dd><a href="javascript:;">CIa>dd>
<dd><a href="javascript:;">CDa>dd>
<dd><a href="">超链接a>dd>
dl>
li>
<li class="layui-nav-item"><a href="javascript:;">k8sa>li>
<li class="layui-nav-item"><a href="">邮箱系统a>li>
ul>
div>
div>
<div class="layui-body">
<div class="layui-container">
常规布局(以中型屏幕桌面为例):
<div class="layui-row">
<div class="layui-col-md9">
<div style="background-color: red;">你的内容 9/12div>
div>
<div class="layui-col-md3">
<div style="background-color: blue;">你的内容 3/12div>
div>
div>
移动设备、平板、桌面端的不同表现:
<div class="layui-row" style="background-color: orange;">
<div class="layui-col-xs6 layui-col-sm6 layui-col-md4" style="background-color: aqua;">
移动:6/12 | 平板:6/12 | 桌面:4/12
div>
<div class="layui-col-xs6 layui-col-sm6 layui-co l-md4" style="background-color:bisque;">
移动:6/12 | 平板:6/12 | 桌面:4/12
div>
<div class="layui-col-xs4 layui-col-sm12 layui-col-md4" style="background-color:blueviolet;">
移动:4/12 | 平板:12/12 | 桌面:4/12
div>
<div class="layui-col-xs4 layui-col-sm7 layui-col-md8" style="background-color:yellow;">
移动:4/12 | 平板:7/12 | 桌面:8/12
div>
<div class="layui-col-xs4 layui-col-sm5 layui-col-md4" style="background-color:violet;">
移动:4/12 | 平板:5/12 | 桌面:4/12
div>
div>
div>
div>
<div class="layui-footer">
底部固定区域www.test.com
div>
div>
<script src="/static/layui/layui.js">script>
<script>
//JS
layui.use(['element', 'layer', 'util'], function () {
var element = layui.element
, layer = layui.layer
, util = layui.util
, $ = layui.$;
//头部事件
util.event('lay-header-event', {
//左侧菜单事件
menuLeft: function (othis) {
layer.msg('展开左侧菜单的操作', { icon: 0 });
}
, menuRight: function () {
layer.open({
type: 1
, content: '处理右侧面板的操作'
, area: ['260px', '100%']
, offset: 'rt' //右上角
, anim: 5
, shadeClose: true
});
}
});
});
script>
body>
html>
现有index.html更该名字为base.html
并再里边定义变量
DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>
{% block title %}
{% endblock %}
title>
<link rel="stylesheet" href="/static/layui/css/layui.css">
head>
<body>
<div class="layui-layout layui-layout-admin">
<div class="layui-header layui-bg-cyan">
<div class="layui-logo layui-hide-xs layui-bg-black" style="font-size: 26px;">运维管理平台div>
<ul class="layui-nav layui-layout-left">
<li class="layui-nav-item layui-show-xs-inline-block layui-hide-sm" lay-header-event="menuLeft">
<i class="layui-icon layui-icon-spread-left">i>
li>
ul>
<ul class="layui-nav layui-layout-right">
<li class="layui-nav-item layui-hide layui-show-md-inline-block">
<a href="javascript:;">
<img src="//tva1.sinaimg.cn/crop.0.0.118.118.180/5db11ff4gw1e77d3nqrv8j203b03cweg.jpg"
class="layui-nav-img">
用户
a>
<dl class="layui-nav-child">
<dd><a href="">个人信息a>dd>
<dd><a href="">设置a>dd>
<dd><a href="">退出a>dd>
dl>
li>
<li class="layui-nav-item" lay-header-event="menuRight" lay-unselect>
<a href="javascript:;">
<i class="layui-icon layui-icon-more-vertical">i>
a>
li>
ul>
div>
<div class="layui-side layui-bg-black">
<div class="layui-side-scroll layui-bg-cyan">
<ul class="layui-nav layui-nav-tree layui-bg-cyan" lay-filter="test">
<li class="layui-nav-item layui-nav-itemed">
<a class="" href="javascript:;"><i
class="layui-icon layui-icon-face-smile">i> 其他系统a>
<dl class="layui-nav-child">
<dd><a href="javascript:;">OAa>dd>
<dd><a href="javascript:;">人事a>dd>
<dd><a href="javascript:;">考核a>dd>
<dd><a href="">the linksa>dd>
dl>
li>
<li class="layui-nav-item">
<a href="javascript:;">自动化a>
<dl class="layui-nav-child">
<dd><a href="javascript:;">CIa>dd>
<dd><a href="javascript:;">CDa>dd>
<dd><a href="">超链接a>dd>
dl>
li>
<li class="layui-nav-item"><a href="javascript:;">k8sa>li>
<li class="layui-nav-item"><a href="">邮箱系统a>li>
ul>
div>
div>
<div class="layui-body" style="background-color: #eeeeee;">
<div style="padding: 15px;">{% block content %}
{% endblock %}div>
div>
<div class="layui-footer">
底部固定区域www.test.com
div>
div>
<script src="/static/layui/layui.js">script>
{% block js %}
{% endblock %}
<script>
//JS
layui.use(['element', 'layer', 'util'], function () {
var element = layui.element
, layer = layui.layer
, util = layui.util
, $ = layui.$;
//头部事件
util.event('lay-header-event', {
//左侧菜单事件
menuLeft: function (othis) {
layer.msg('展开左侧菜单的操作', { icon: 0 });
}
, menuRight: function () {
layer.open({
type: 1
, content: '处理右侧面板的操作'
, area: ['260px', '100%']
, offset: 'rt' //右上角
, anim: 5
, shadeClose: true
});
}
});
});
script>
body>
html>
{% extends 'base.html' %}
{% block content %}
<div class="layui-row layui-col-space10">
<div class="layui-col-md6">
<div class="layui-card">
<div class="layui-card-header">卡片面板div>
<div class="layui-card-body">
卡片式面板面板通常用于非白色背景色的主体内<br>
从而映衬出边框投影
div>
div>
div>
<div class="layui-col-md6">
<div class="layui-card">
<div class="layui-card-header">卡片面板div>
<div class="layui-card-body">
卡片式面板面板通常用于非白色背景色的主体内<br>
从而映衬出边框投影
div>
div>
div>
div>
{% endblock content %}
{% extends 'base.html' %}
{% block content %}
基础按钮<br>
<button type="button" class="layui-btn">一个标准的按钮button><br>
<a href="http://www.baidu.com" class="layui-btn">一个可跳转的按钮a><br>
<div class="layui-btn">一个按钮div>
不同主题的按钮<br>
<button type="button" class="layui-btn layui-btn-primary">原始按钮button><br>
<button type="button" class="layui-btn">默认按钮button><br>
<button type="button" class="layui-btn layui-btn-normal">百搭按钮button><br>
<button type="button" class="layui-btn layui-btn-warm">暖色按钮button><br>
<button type="button" class="layui-btn layui-btn-danger">警告按钮button><br>
<button type="button" class="layui-btn layui-btn-disabled">禁用按钮button><br>
按钮尺寸<br>
<button type="button" class="layui-btn layui-btn-primary layui-btn-1g">大型按钮button>
<button type="button" class="layui-btn layui-btn-primary">默认按钮button>
<button type="button" class="layui-btn layui-btn-primary layui-btn-sm">小型按钮button>
<button type="button" class="layui-btn layui-btn-primary layui-btn-xs">迷你按钮button><br>
圆角按钮<br>
<button type="button" class="layui-btn layui-btn-primary layui-btn-radius">原始按钮button>
<button type="button" class="layui-btn layui-btn-radius">默认按钮button>
<button type="button" class="layui-btn layui-btn-normal layui-btn-radius">百搭按钮button>
<button type="button" class="layui-btn layui-btn-warm layui-btn-radius">暖色按钮button>
<button type="button" class="layui-btn layui-btn-danger layui-btn-radius">警告按钮button>
<button type="button" class="layui-btn layui-btn-disabled layui-btn-radius">禁用按钮button><br>
图标按钮<br>
<button type="button" class="layui-btn"><i class="layui-icon layui-icon-addition">增加i>button><br>
<button type="button" class="layui-btn"><i class="layui-icon layui-icon-subtraction">删除i>button><br>
{% endblock content %}
# layui/urls.py
from django.contrib import admin
from django.urls import path,re_path
from mylayui import views
urlpatterns = [
path('admin/', admin.site.urls),
re_path('^$',views.index),
re_path('^user/$', views.user),
]
# mylayui/views.py
from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,'index.html')
def user(request):
if request.method == "GET":
print('11111')
elif request.method == "POST":
print(request.POST)
print(request.POST.get('username'))
print('22222')
code = "0"
msg = "用户添加成功"
result = {'code': code, 'msg': msg}
return JsonResponse(result)
base.html继承上边的不变
{% extends 'base.html' %}
{% block content %}
<form class="layui-form" action="" onsubmit="return false">
{% csrf_token %}
<div class="layui-form-item">
<label class="layui-form-label">用户名label>
<div class="layui-input-block">
<input type="text" name="username" required lay-verify="required" placeholder="请输入用户名" autocomplete="off"
class="layui-input">
div>
div>
<div class="layui-form-item">
<label class="layui-form-label">密码label>
<div class="layui-input-inline">
<input type="password" name="password" required lay-verify="required" placeholder="请输入密码" autocomplete="off"
class="layui-input">
div>
<div class="layui-form-mid layui-word-aux">辅助文字div>
div>
<div class="layui-form-item">
<label class="layui-form-label">兴趣爱好label>
<div class="layui-input-block">
<input type="checkbox" name="like[write]" title="写作">
<input type="checkbox" name="like[read]" title="阅读" checked>
<input type="checkbox" name="like[dai]" title="发呆">
div>
div>
<div class="layui-form-item">
<label class="layui-form-label">是否启用label>
<div class="layui-input-block">
<input type="checkbox" name="status" lay-skin="switch">
div>
div>
<div class="layui-form-item">
<label class="layui-form-label">性别label>
<div class="layui-input-block">
<input type="radio" name="sex" value="男" title="男">
<input type="radio" name="sex" value="女" title="女" checked>
div>
div>
<div class="layui-form-item layui-form-text">
<label class="layui-form-label">备注label>
<div class="layui-input-block">
<textarea name="desc" placeholder="请输入内容" class="layui-textarea">textarea>
div>
div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit lay-filter="formDemo">立即提交button>
<button type="reset" class="layui-btn layui-btn-primary">重置button>
div>
div>
form>
{% endblock %}
{% block js %}
<script>
// 使用Layui的表单模块
layui.use(['form','layer'], function () {
var form = layui.form;
var $ = layui.jquery;
var layer = layui.layer;
// 监听提交
form.on('submit(formDemo)', function (data) {
$.ajax({
type: "POST",
url: "/user/",
data: data.field,
success: function (result) {
if (result.code == "0" ) {
layer.msg(result.msg, {icon:6})
} else {
layer.msg(result.msg, {icon:5})
}
}
})
});
});
script>
{% endblock %}
# layui/urls.py
from django.contrib import admin
from django.urls import path,re_path
from mylayui import views
urlpatterns = [
path('admin/', admin.site.urls),
re_path('^$',views.index),
re_path('^upload/$', views.upload),
]
# mylayui/views.py
from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,'index.html')
def upload(request):
if request.method == "GET":
print('getgggggggggg')
elif request.method == "POST":
print(request.POST)
file_obj = request.FILES.get("file")
import os
file_path = os.path.join('upload', file_obj.name)
with open(file_path, mode='wb') as f:
for i in file_obj.chunks():
f.write(i)
print('postpppppppppp')
code = "0"
msg = "用户添加成功"
result = {'code': code, 'msg': msg}
return JsonResponse(result)
base.html继承上边的不变
{% extends 'base.html' %}
{% block content %}
<form class="layui-form" action="" onsubmit="return false">
{% csrf_token %}
<div class="layui-form-item">
<label class="layui-form-label">上传头像label>
<button type="button" class="layui-btn" id="uploadFile"><i class="layui-icon">i>上传文件button>
div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit lay-filter="formDemo" id="uploadBtn" >立即提交button>
<button type="reset" class="layui-btn layui-btn-primary">重置button>
div>
div>
form>
{% endblock %}
{% block js %}
<script>
//Demo
layui.use(['form', 'layer', 'upload'], function () {
var form = layui.form;
var $ = layui.jquery;
var layer = layui.layer;
var upload = layui.upload;
upload.render({
elem: "#uploadFile", // 选择上传按钮
url: "/upload/", // 服务端上传接口
auto: false, // 是否选中文件后自动上传
bindAction: "#uploadBtn", // 绑定提交表单的按钮
before: function () {
this.data = {
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
}
},
done: function (result) {
if (result.code == "0") {
layer.msg(result.msg, { icon: 6 })
} else {
layer.msg(result.msg, { icon: 5 })
}
}
});
});
script>
{% endblock %}
# layui/urls.py
from django.contrib import admin
from django.urls import path,re_path
from mylayui import views
urlpatterns = [
path('admin/', admin.site.urls),
re_path('^$',views.index),
]
# mylayui/views.py
from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,'index.html')
base.html继承上边的不变
{% extends 'base.html' %}
{% block title %}
数据表格
{% endblock %}
{% block content %}
<div class="layui-card">
<div class="layui-card-body">
<table class="layui-table">
<colgroup>
<col width="150">
<col width="200">
<col>
colgroup>
<thead>
<tr>
<th>昵称th>
<th>加入时间th>
<th>签名th>
tr>
thead>
<tbody>
<tr>
<td>贤心td>
<td>2016-11-29td>
<td>人生就像是一场修行td>
tr>
<tr>
<td>许闲心td>
<td>2016-11-28td>
<td>于千万人之中遇见你所遇见的人,于千万年之中,时间的无涯的荒野里…td>
tr>
tbody>
table>
div>
div>
{% endblock %}
{% block js %}
{% endblock %}
方式 | 机制 | 适用场景 | |
---|---|---|---|
01. | 方法渲染 | 用JS方法的配置完成渲染 | (推荐)无需写过多的 HTML,在 JS 中指定原始元素,再设定各项参数即可。 |
02. | 自动渲染 | HTML配置,自动渲染 | 无需写过多 JS,可专注于 HTML 表头部分 |
03. | 转换静态表格 | 转化一段已有的表格元素 | 无需配置数据接口,在JS中指定表格元素,并简单地给表头加上自定义属性即可 |
# layui/urls.py
from django.contrib import admin
from django.urls import path,re_path
from mylayui import views
urlpatterns = [
path('admin/', admin.site.urls),
re_path('^$',views.index),
re_path('^liebiao/$', views.liebiao),
]
# mylayui/views.py
from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,'index.html')
def liebiao(request):
if request.method == "GET":
data = []
for id in range(1,15):
import random
name = random.sample(['风','火','雷','电'],1)
name = '姓' + name[0]
sex = random.sample(['男','女'],1)
sex = sex[0]
city = random.sample(['北京','上海','深圳','广州','邯郸','邱县'],1)
city = city[0]
row = {'id':id,'username':name,'sex':sex,'city':city}
data.append(row)
code = "0"
msg = "获取数据成功"
count = len(data)
result = {'code':code,'msg':msg,'count':count,'data':data}
return JsonResponse(result)
base.html继承上边的不变
{% extends 'base.html' %}
{% block title %}
数据表格
{% endblock %}
{% block content %}
<div class="layui-card">
<div class="layui-card-body">
<table id="demo" lay-filter="test">table>
div>
div>
{% endblock %}
{% block js %}
<script>
layui.use(['layer', 'table'], function () {
var table = layui.table
var $ = layui.jquery;
table.render({
elem: '#demo'
, url: '/liebiao/'
, title: '用户数据表'
, cols: [[
{ field: 'id', title: 'ID', width: 80, fixed: 'left', unresize: true, sort: true },
{ field: 'username', title: '用户名', width: 120 },
{ field: 'sex', title: '性别', width: 120 },
{ field: 'city', title: '城市' },
]]
});
})
script>
{% endblock %}
# layui/urls.py
from django.contrib import admin
from django.urls import path,re_path
from mylayui import views
urlpatterns = [
path('admin/', admin.site.urls),
re_path('^$',views.index),
re_path('^liebiao/$', views.liebiao),
]
# mylayui/views.py
from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,'index.html')
def liebiao(request):
if request.method == "GET":
data = []
for id in range(1,15):
import random
name = random.sample(['风','火','雷','电'],1)
name = '姓' + name[0]
sex = random.sample(['男','女'],1)
sex = sex[0]
city = random.sample(['北京','上海','深圳','广州','邯郸','邱县'],1)
city = city[0]
row = {'id':id,'username':name,'sex':sex,'city':city}
data.append(row)
count = len(data)
page = int(request.GET.get('page',1))
limit = int(request.GET.get('limit'))
start = (page-1) * limit
end = page * limit
data = data[start:end]
code = "0"
msg = "获取数据成功"
result = {'code':code,'msg':msg,'count':count,'data':data}
return JsonResponse(result)
base.html继承上边的不变
{% extends 'base.html' %}
{% block title %}
数据表格
{% endblock %}
{% block content %}
<div class="layui-card">
<div class="layui-card-body">
<table id="demo" lay-filter="test">table>
div>
div>
{% endblock %}
{% block js %}
<script>
layui.use(['layer', 'table'], function () {
var table = layui.table
var $ = layui.jquery;
table.render({
elem: '#demo'
, url: '/liebiao/'
, title: '用户数据表'
, cols: [[
{ field: 'id', title: 'ID', width: 80, fixed: 'left', unresize: true, sort: true },
{ field: 'username', title: '用户名', width: 120 },
{ field: 'sex', title: '性别', width: 120 },
{ field: 'city', title: '城市' },
]]
, page: true
});
})
script>
{% endblock %}
# layui/urls.py
from django.contrib import admin
from django.urls import path,re_path
from mylayui import views
urlpatterns = [
path('admin/', admin.site.urls),
re_path('^$',views.index),
re_path('^liebiao/$', views.liebiao),
]
# mylayui/views.py
from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,'index.html')
def liebiao(request):
if request.method == "GET":
data = []
for id in range(1,15):
import random
name = random.sample(['风','火','雷','电'],1)
name = '姓' + name[0]
sex = random.sample(['男','女'],1)
sex = sex[0]
city = random.sample(['北京','上海','深圳','广州','邯郸','邱县'],1)
city = city[0]
row = {'id':id,'username':name,'sex':sex,'city':city}
data.append(row)
count = len(data)
page = int(request.GET.get('page',1))
limit = int(request.GET.get('limit'))
start = (page-1) * limit
end = page * limit
data = data[start:end]
code = "0"
msg = "获取数据成功"
result = {'code':code,'msg':msg,'count':count,'data':data}
return JsonResponse(result)
base.html继承上边的不变
{% extends 'base.html' %}
{% block title %}
数据表格
{% endblock %}
{% block content %}
<div class="layui-card">
<div class="layui-card-body">
<table id="demo" lay-filter="test">table>
<script type="text/html" id="toolbarDemo">
<div class="layui-btn-container">
<button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>
<button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>
<button class="layui-btn layui-btn-sm" lay-event="isAll">验证是否全选</button>
</div>
script>
<script type="text/html" id="barDemo">
<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
script>
div>
div>
{% endblock %}
{% block js %}
<script>
layui.use(['layer', 'table'], function () {
var table = layui.table
var $ = layui.jquery;
table.render({
elem: '#demo',
url: '/liebiao/',
title: '用户数据表',
toolbar: '#toolbarDemo', //开启头部工具栏,并为其绑定左侧模板
defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义,去除该参数即可
title: '提示'
, layEvent: 'LAYTABLE_TIPS'
, icon: 'layui-icon-tips'
}],
cols: [[
{ type: 'checkbox', fixed: 'left' },
{ field: 'id', title: 'ID', width: 80, fixed: 'left', unresize: true, sort: true },
{ field: 'username', title: '用户名', width: 120 },
{ field: 'sex', title: '性别', width: 120 },
{ field: 'city', title: '城市' },
{ fixed: 'right', title: '操作', toolbar: '#barDemo', width: 150 }
]],
page: true
});
//监听行工具事件
table.on('tool(test)', function (obj) {
var data = obj.data;
//console.log(obj)
if (obj.event === 'del') {
layer.confirm('真的删除行么', function (index) {
obj.del();
layer.close(index);
});
} else if (obj.event === 'edit') {
layer.prompt({
formType: 2
, value: data.email
}, function (value, index) {
obj.update({
email: value
});
layer.close(index);
});
}
});
//头工具栏事件
table.on('toolbar(test)', function (obj) {
var checkStatus = table.checkStatus(obj.config.id);
switch (obj.event) {
case 'getCheckData':
var data = checkStatus.data;
layer.alert(JSON.stringify(data));
break;
case 'getCheckLength':
var data = checkStatus.data;
layer.msg('选中了:' + data.length + ' 个');
break;
case 'isAll':
layer.msg(checkStatus.isAll ? '全选' : '未全选');
break;
//自定义头工具栏右侧图标 - 提示
case 'LAYTABLE_TIPS':
layer.alert('这是工具栏右侧自定义的一个图标按钮');
break;
};
});
});
script>
{% endblock %}
# layui/urls.py
from django.contrib import admin
from django.urls import path,re_path
from mylayui import views
urlpatterns = [
path('admin/', admin.site.urls),
re_path('^$',views.index),
re_path('^liebiao/$', views.liebiao),
]
# mylayui/views.py
from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,'index.html')
def liebiao(request):
if request.method == "GET":
data = []
for id in range(1,15):
import random
name = random.sample(['风','火','雷','电'],1)
name = '姓' + name[0]
sex = random.sample(['男','女'],1)
sex = sex[0]
city = random.sample(['北京','上海','深圳','广州','邯郸','邱县'],1)
city = city[0]
row = {'id':id,'username':name,'sex':sex,'city':city}
data.append(row)
count = len(data)
page = int(request.GET.get('page',1))
limit = int(request.GET.get('limit'))
start = (page-1) * limit
end = page * limit
data = data[start:end]
code = "0"
msg = "获取数据成功"
result = {'code':code,'msg':msg,'count':count,'data':data}
return JsonResponse(result)
if request.method == "POST":
print(request.POST)
code = '0'
msg = '删除成功'
result = {'code':code,'msg':msg}
return JsonResponse(result)
base.html继承上边的不变
{% extends 'base.html' %}
{% block title %}
数据表格
{% endblock %}
{% block content %}
{% csrf_token %}
<div class="layui-card">
<div class="layui-card-body">
<table id="demo" lay-filter="test">table>
<script type="text/html" id="toolbarDemo">
<div class="layui-btn-container">
<button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>
<button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>
<button class="layui-btn layui-btn-sm" lay-event="isAll">验证是否全选</button>
</div>
script>
<script type="text/html" id="barDemo">
<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
script>
div>
div>
{% endblock %}
{% block js %}
<script>
layui.use(['layer', 'table'], function () {
var table = layui.table
var $ = layui.jquery;
table.render({
elem: '#demo',
url: '/liebiao/',
title: '用户数据表',
toolbar: '#toolbarDemo', //开启头部工具栏,并为其绑定左侧模板
defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义,去除该参数即可
title: '提示'
, layEvent: 'LAYTABLE_TIPS'
, icon: 'layui-icon-tips'
}],
cols: [[
{ type: 'checkbox', fixed: 'left' },
{ field: 'id', title: 'ID', width: 80, fixed: 'left', unresize: true, sort: true },
{ field: 'username', title: '用户名', width: 120 },
{ field: 'sex', title: '性别', width: 120 },
{ field: 'city', title: '城市' },
{ fixed: 'right', title: '操作', toolbar: '#barDemo', width: 150 }
]],
page: true
});
//头工具栏事件
table.on('toolbar(test)', function (obj) {
var checkStatus = table.checkStatus(obj.config.id);
switch (obj.event) {
case 'getCheckData':
var data = checkStatus.data;
layer.alert(JSON.stringify(data));
break;
case 'getCheckLength':
var data = checkStatus.data;
layer.msg('选中了:' + data.length + ' 个');
break;
case 'isAll':
layer.msg(checkStatus.isAll ? '全选' : '未全选');
break;
//自定义头工具栏右侧图标 - 提示
case 'LAYTABLE_TIPS':
layer.alert('这是工具栏右侧自定义的一个图标按钮');
break;
};
});
//监听行工具事件
table.on('tool(test)', function (obj) {
var data = obj.data;
//console.log(obj)
if (obj.event === 'del') {
layer.confirm('真的删除行么', function (index) {
// obj.del();
// layer.close(index);
csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val()
var post_data = {
'id': data.id,
'csrfmiddlewaretoken': csrfmiddlewaretoken
}
$.ajax({
type: "POST",
url: "/liebiao/",
data: post_data,
success: function (result) {
if (result.code == "0") {
layer.msg(result.msg, { icon: 6 })
} else {
layer.msg(result.msg, { icon: 5 })
}
}
})
});
} else if (obj.event === 'edit') {
layer.prompt({
formType: 2
, value: data.email
}, function (value, index) {
obj.update({
email: value
});
layer.close(index);
});
}
});
});
script>
{% endblock %}
# layui/urls.py
from django.contrib import admin
from django.urls import path,re_path
from mylayui import views
urlpatterns = [
path('admin/', admin.site.urls),
re_path('^$',views.index),
re_path('^liebiao/$', views.liebiao),
]
# mylayui/views.py
from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,'index.html')
def liebiao(request):
if request.method == "GET":
data = []
for id in range(1,15):
import random
name = random.sample(['风','火','雷','电'],1)
name = '姓' + name[0]
sex = random.sample(['男','女'],1)
sex = sex[0]
city = random.sample(['北京','上海','深圳','广州','邯郸','邱县'],1)
city = city[0]
row = {'id':id,'username':name,'sex':sex,'city':city}
# data.append(row)
# 根据查询关键字返回数据
search_key = request.GET.get('searchKey', None)
print(search_key)
if search_key:
if search_key == name: # in 相当于模糊查询
data.append(row)
else:
data.append(row)
# 分页
count = len(data)
page = int(request.GET.get('page',1))
limit = int(request.GET.get('limit'))
start = (page-1) * limit
end = page * limit
data = data[start:end]
code = "0"
msg = "获取数据成功"
result = {'code':code,'msg':msg,'count':count,'data':data}
return JsonResponse(result)
if request.method == "POST":
print(request.POST)
code = '0'
msg = '删除成功'
result = {'code':code,'msg':msg}
return JsonResponse(result)
base.html继承上边的不变
{% extends 'base.html' %}
{% block title %}
数据表格
{% endblock %}
{% block content %}
{% csrf_token %}
<div class="layui-card">
<div class="layui-card-body">
<table id="demo" lay-filter="test">table>
<script type="text/html" id="toolbarDemo">
<!-- 搜索框 -->
<input type="text" name="username" class="layui-input" style="width: 150px;float: left;">
<button class="layui-btn" style="float: left;" id="searchBtn">搜索</button><br><br>
<!-- 头部按钮 -->
<div class="layui-btn-container">
<button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>
<button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>
<button class="layui-btn layui-btn-sm" lay-event="isAll">验证是否全选</button>
</div>
script>
<script type="text/html" id="barDemo">
<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
script>
div>
div>
{% endblock %}
{% block js %}
<script>
layui.use(['layer', 'table'], function () {
var table = layui.table
var $ = layui.jquery;
// 渲染表格
table.render({
elem: '#demo',
url: '/liebiao/',
title: '用户数据表',
toolbar: '#toolbarDemo', //开启头部工具栏,并为其绑定左侧模板
defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义,去除该参数即可
title: '提示'
, layEvent: 'LAYTABLE_TIPS'
, icon: 'layui-icon-tips'
}],
cols: [[
{ type: 'checkbox', fixed: 'left' },
{ field: 'id', title: 'ID', width: 80, fixed: 'left', unresize: true, sort: true },
{ field: 'username', title: '用户名', width: 120 },
{ field: 'sex', title: '性别', width: 120 },
{ field: 'city', title: '城市' },
{ fixed: 'right', title: '操作', toolbar: '#barDemo', width: 150 }
]],
page: true,
id:'USER' // 表格的唯一标识,用于刷新
});
//头工具栏事件
table.on('toolbar(test)', function (obj) {
var checkStatus = table.checkStatus(obj.config.id);
switch (obj.event) {
case 'getCheckData':
var data = checkStatus.data;
layer.alert(JSON.stringify(data));
break;
case 'getCheckLength':
var data = checkStatus.data;
layer.msg('选中了:' + data.length + ' 个');
break;
case 'isAll':
layer.msg(checkStatus.isAll ? '全选' : '未全选');
break;
//自定义头工具栏右侧图标 - 提示
case 'LAYTABLE_TIPS':
layer.alert('这是工具栏右侧自定义的一个图标按钮');
break;
};
});
//监听行工具事件
table.on('tool(test)', function (obj) {
var data = obj.data;
//console.log(obj)
if (obj.event === 'del') {
layer.confirm('真的删除行么', function (index) {
// 执行删除操作
// obj.del();
// layer.close(index);
csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val()
var post_data = {
'id': data.id,
'csrfmiddlewaretoken': csrfmiddlewaretoken
}
$.ajax({
type: "POST",
url: "/liebiao/",
data: post_data,
success: function (result) {
if (result.code == "0") {
layer.msg(result.msg, { icon: 6 })
} else {
layer.msg(result.msg, { icon: 5 })
}
}
})
});
} else if (obj.event === 'edit') {
// 执行编辑操作
layer.prompt({
formType: 2
, value: data.email
}, function (value, index) {
obj.update({
email: value
});
layer.close(index);
});
}
});
// 搜索按钮点击事件
$(document).on('click', "#searchBtn", function () {
// $("#searchBtn").click(function () {
var input_val = $('input[name=username]').val();
layer.msg(input_val)
// 重新加载表格数据,传递搜索关键字
table.reload('USER',{
where: {
searchKey:input_val
},
page:{
curr:1
}
});
});
});
script>
{% endblock %}
# layui/urls.py
from django.contrib import admin
from django.urls import path,re_path
from mylayui import views
urlpatterns = [
path('admin/', admin.site.urls),
re_path('^$',views.index),
re_path('^liebiao/$', views.liebiao),
]
# mylayui/views.py
from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,'index.html')
def liebiao(request):
if request.method == "GET":
data = []
# 生成模拟数据
for id in range(1, 15):
import random
# 随机生成姓
name = '姓' + random.choice(['风', '火', '雷', '电'])
# 随机生成性别
sex = random.choice(['男', '女'])
# 随机生成城市
city = random.choice(['北京', '上海', '深圳', '广州', '邯郸', '邱县'])
row = {'id': id, 'username': name, 'sex': sex, 'city': city}
# 根据查询关键字返回数据
search_key = request.GET.get('searchKey', None)
sexKey = request.GET.get('sexKey', None)
if search_key or sexKey:
# 使用 in 进行模糊查询
if search_key == name:
data.append(row)
elif sexKey == sex:
data.append(row)
else:
data.append(row)
# 分页
count = len(data)
page = int(request.GET.get('page', 1))
limit = int(request.GET.get('limit'))
start = (page - 1) * limit
end = page * limit
data = data[start:end]
code = "0"
msg = "获取数据成功"
result = {'code': code, 'msg': msg, 'count': count, 'data': data}
return JsonResponse(result)
if request.method == "POST":
print(request.POST)
code = '0'
msg = '删除成功'
result = {'code': code, 'msg': msg}
return JsonResponse(result)
base.html继承上边的不变
{% extends 'base.html' %}
{% block title %}
数据表格
{% endblock %}
{% block content %}
{% csrf_token %}
<div class="layui-card">
<div class="layui-card-body">
<table id="demo" lay-filter="test">table>
<script type="text/html" id="toolbarDemo">
<!-- 搜索框 -->
<input type="text" name="username" class="layui-input" style="width: 150px;float: left;">
<button class="layui-btn" style="float: left;" id="searchBtn">搜索</button>
<!-- 直接选择或搜索选择 -->
<div class="layui-input-inline">
<select name="sex" lay-verify="required" lay-search="" lay-filter="sex">
<option value="">性别</option>
<option value="男">男</option>
<option value="女">女</option>
</select>
</div>
<br>
<br>
<!-- 头部按钮 -->
<!-- <div class="layui-btn-container">
<button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>
<button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>
<button class="layui-btn layui-btn-sm" lay-event="isAll">验证是否全选</button>
</div> -->
script>
<script type="text/html" id="barDemo">
<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
script>
div>
div>
{% endblock %}
{% block js %}
<script>
layui.use(['layer', 'table', 'form'], function () {
var table = layui.table;
var layer = layui.layer;
var $ = layui.jquery;
var form = layui.form;
// 渲染表格
table.render({
elem: '#demo',
url: '/liebiao/',
title: '用户数据表',
toolbar: '#toolbarDemo', //开启头部工具栏,并为其绑定左侧模板
defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义,去除该参数即可
title: '提示'
, layEvent: 'LAYTABLE_TIPS'
, icon: 'layui-icon-tips'
}],
cols: [[
{ type: 'checkbox', fixed: 'left' },
{ field: 'id', title: 'ID', width: 80, fixed: 'left', unresize: true, sort: true },
{ field: 'username', title: '用户名', width: 120 },
{ field: 'sex', title: '性别', width: 120},
{ field: 'city', title: '城市' },
{ fixed: 'right', title: '操作', toolbar: '#barDemo', width: 150 }
]],
page: true,
id: 'USER' // 表格的唯一标识,用于刷新
});
//头工具栏事件
table.on('toolbar(test)', function (obj) {
var checkStatus = table.checkStatus(obj.config.id);
switch (obj.event) {
case 'getCheckData':
var data = checkStatus.data;
layer.alert(JSON.stringify(data));
break;
case 'getCheckLength':
var data = checkStatus.data;
layer.msg('选中了:' + data.length + ' 个');
break;
case 'isAll':
layer.msg(checkStatus.isAll ? '全选' : '未全选');
break;
//自定义头工具栏右侧图标 - 提示
case 'LAYTABLE_TIPS':
layer.alert('这是工具栏右侧自定义的一个图标按钮');
break;
};
});
//监听行工具事件
table.on('tool(test)', function (obj) {
var data = obj.data;
//console.log(obj)
if (obj.event === 'del') {
layer.confirm('真的删除行么', function (index) {
// 执行删除操作
// obj.del();
// layer.close(index);
csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val()
var post_data = {
'id': data.id,
'csrfmiddlewaretoken': csrfmiddlewaretoken
}
$.ajax({
type: "POST",
url: "/liebiao/",
data: post_data,
success: function (result) {
if (result.code == "0") {
layer.msg(result.msg, { icon: 6 })
} else {
layer.msg(result.msg, { icon: 5 })
}
}
})
});
} else if (obj.event === 'edit') {
// 执行编辑操作
layer.prompt({
formType: 2
, value: data.email
}, function (value, index) {
obj.update({
email: value
});
layer.close(index);
});
}
});
// 搜索按钮点击事件
$(document).on('click', "#searchBtn", function () {
// $("#searchBtn").click(function () {
var input_val = $('input[name=username]').val();
// layer.msg(input_val)
// 重新加载表格数据,传递搜索关键字
table.reload('USER', {
where: {
searchKey: input_val
},
page: {
curr: 1
}
});
});
form.on('select(sex)', function (data) {
// $(document).on('click', "#sex", function () {
// var sex = $('input[sex=sex]').val();
table.reload('USER', {
where: { //设定异步数据接口的额外参数,任意设
sexKey: data.value,
},
page: {
curr: 1 //重新从第 1 页开始
}
}); //只重载数据
})
});
script>
{% endblock %}
templet 提供了三种使用方式,请结合实际场景选择最合适的一种:
- 如果自定义模版的字符量太大,我们推荐你采用【方式一】;
- 如果自定义模板的字符量适中,或者想更方便地调用外部方法,我们推荐你采用【方式二】;
- 如果自定义模板的字符量很小,我们推荐你采用【方式三】
方式一:绑定模版选择器
table.render({
cols: [[
{field:'title', title: '文章标题', width: 200, templet: '#titleTpl'} //这里的templet值是模板元素的选择器
,{field:'id', title:'ID', width:100}
]]
});
等价于:
<th lay-data="{field:'title', width: 200, templet: '#titleTpl'}">文章标题th>
<th lay-data="{field:'id', width:100}">IDth>
下述是templet对应的模板,它可以存放在页面的任意位置。模板遵循于 laytpl 语法,可读取到返回的所有数据
<script type="text/html" id="titleTpl">
<a href="/detail/{{d.id}}" class="layui-table-link">{{d.title}}</a>
script>
注意:上述的 {{d.id}}、{{d.title}} 是动态内容,它对应数据接口返回的字段名。除此之外,你还可以读取到以下额外字段:
序号:{{ d.LAY_INDEX }}
当前列的表头信息:{{ d.LAY_COL }} (layui 2.6.8 新增)
由于模板遵循 laytpl 语法(建议细读 laytpl文档 ),因此在模板中你可以写任意脚本语句(如 if else/for等):
<script type="text/html" id="titleTpl">
{{# if(d.id < 100){ }}
<a href="/detail/{{d.id}}" class="layui-table-link">{{d.title}}</a>
{{# } else { }}
{{d.title}}(普通用户)
{{# } }}
script>
方式二:函数转义
table.render({
cols: [[
{field:'title', title: '文章标题', width: 200
,templet: function(d){
console.log(d.LAY_INDEX); //得到序号。一般不常用
console.log(d.LAY_COL); //得到当前列表头配置信息(layui 2.6.8 新增)。一般不常用
//得到当前行数据,并拼接成自定义模板
return 'ID:'+ d.id +',标题:<span style="color: #c00;">'+ d.title +'span>'
}
}
,{field:'id', title:'ID', width:100}
]]
});
**方式三:直接赋值模版字符.**事实上,templet 也可以直接是一段 html 内容,如:
templet: '<div><a href="/detail/{{d.id}}" class="layui-table-link">{{d.title}}a>div>'
注意:这里一定要被一层 <div>div> 包裹,否则无法读取到模板
# layui/urls.py
from django.contrib import admin
from django.urls import path,re_path
from mylayui import views
urlpatterns = [
path('admin/', admin.site.urls),
re_path('^$',views.index),
re_path('^liebiao/$', views.liebiao),
]
# mylayui/views.py
from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,'index.html')
def liebiao(request):
if request.method == "GET":
data = []
# 生成模拟数据
for id in range(1, 15):
import random
# 随机生成姓
name = '姓' + random.choice(['风', '火', '雷', '电'])
# 随机生成性别
sex = random.choice(['男', '女'])
# 随机生成城市
city = random.choice(['北京', '上海', '深圳', '广州', '邯郸', '邱县'])
row = {'id': id, 'username': name, 'sex': sex, 'city': city}
# 根据查询关键字返回数据
search_key = request.GET.get('searchKey', None)
sexKey = request.GET.get('sexKey', None)
if search_key or sexKey:
# 使用 in 进行模糊查询
if search_key == name:
data.append(row)
elif sexKey == sex:
data.append(row)
else:
data.append(row)
# 分页
count = len(data)
page = int(request.GET.get('page', 1))
limit = int(request.GET.get('limit'))
start = (page - 1) * limit
end = page * limit
data = data[start:end]
code = "0"
msg = "获取数据成功"
result = {'code': code, 'msg': msg, 'count': count, 'data': data}
return JsonResponse(result)
if request.method == "POST":
print(request.POST)
code = '0'
msg = '删除成功'
result = {'code': code, 'msg': msg}
return JsonResponse(result)
base.html继承上边的不变
{% extends 'base.html' %}
{% block title %}
数据表格
{% endblock %}
{% block content %}
{% csrf_token %}
<div class="layui-card">
<div class="layui-card-body">
<table id="demo" lay-filter="test">table>
<script type="text/html" id="toolbarDemo">
<!-- 搜索框 -->
<input type="text" name="username" class="layui-input" style="width: 150px;float: left;">
<button class="layui-btn" style="float: left;" id="searchBtn">搜索</button>
<!-- 直接选择或搜索选择 -->
<div class="layui-input-inline">
<select name="sex" lay-verify="required" lay-search="" lay-filter="sex">
<option value="">性别</option>
<option value="男">男</option>
<option value="女">女</option>
</select>
</div>
<br>
<br>
<!-- 头部按钮 -->
<!-- <div class="layui-btn-container">
<button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>
<button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>
<button class="layui-btn layui-btn-sm" lay-event="isAll">验证是否全选</button>
</div> -->
script>
<script type="text/html" id="barDemo">
<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
script>
div>
div>
{% endblock %}
{% block js %}
<script>
layui.use(['layer', 'table', 'form'], function () {
var table = layui.table;
var layer = layui.layer;
var $ = layui.jquery;
var form = layui.form;
// 渲染表格
table.render({
elem: '#demo',
url: '/liebiao/',
title: '用户数据表',
toolbar: '#toolbarDemo', //开启头部工具栏,并为其绑定左侧模板
defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义,去除该参数即可
title: '提示'
, layEvent: 'LAYTABLE_TIPS'
, icon: 'layui-icon-tips'
}],
cols: [[
{ type: 'checkbox', fixed: 'left' },
{ field: 'id', title: 'ID', width: 80, fixed: 'left', unresize: true, sort: true },
{ field: 'username', title: '用户名', width: 120 },
{ field: 'sex', title: '性别', width: 120,templet: function (d) {
if (d.sex == "女") {
return '' + d.sex + ''
} else {
return '' + d.sex + ''
}
}},
{ field: 'city', title: '城市' },
{ fixed: 'right', title: '操作', toolbar: '#barDemo', width: 150 }
]],
page: true,
id: 'USER' // 表格的唯一标识,用于刷新
});
//头工具栏事件
table.on('toolbar(test)', function (obj) {
var checkStatus = table.checkStatus(obj.config.id);
switch (obj.event) {
case 'getCheckData':
var data = checkStatus.data;
layer.alert(JSON.stringify(data));
break;
case 'getCheckLength':
var data = checkStatus.data;
layer.msg('选中了:' + data.length + ' 个');
break;
case 'isAll':
layer.msg(checkStatus.isAll ? '全选' : '未全选');
break;
//自定义头工具栏右侧图标 - 提示
case 'LAYTABLE_TIPS':
layer.alert('这是工具栏右侧自定义的一个图标按钮');
break;
};
});
//监听行工具事件
table.on('tool(test)', function (obj) {
var data = obj.data;
//console.log(obj)
if (obj.event === 'del') {
layer.confirm('真的删除行么', function (index) {
// 执行删除操作
// obj.del();
// layer.close(index);
csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val()
var post_data = {
'id': data.id,
'csrfmiddlewaretoken': csrfmiddlewaretoken
}
$.ajax({
type: "POST",
url: "/liebiao/",
data: post_data,
success: function (result) {
if (result.code == "0") {
layer.msg(result.msg, { icon: 6 })
} else {
layer.msg(result.msg, { icon: 5 })
}
}
})
});
} else if (obj.event === 'edit') {
// 执行编辑操作
layer.prompt({
formType: 2
, value: data.email
}, function (value, index) {
obj.update({
email: value
});
layer.close(index);
});
}
});
// 搜索按钮点击事件
$(document).on('click', "#searchBtn", function () {
// $("#searchBtn").click(function () {
var input_val = $('input[name=username]').val();
// layer.msg(input_val)
// 重新加载表格数据,传递搜索关键字
table.reload('USER', {
where: {
searchKey: input_val
},
page: {
curr: 1
}
});
});
form.on('select(sex)', function (data) {
// $(document).on('click', "#sex", function () {
// var sex = $('input[sex=sex]').val();
table.reload('USER', {
where: { //设定异步数据接口的额外参数,任意设
sexKey: data.value,
},
page: {
curr: 1 //重新从第 1 页开始
}
}); //只重载数据
})
});
script>
{% endblock %}
# layui/urls.py
from django.contrib import admin
from django.urls import path,re_path
from mylayui import views
urlpatterns = [
path('admin/', admin.site.urls),
re_path('^$',views.index),
re_path('^liebiao/$', views.liebiao),
]
# mylayui/views.py
from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,'index.html')
def liebiao(request):
if request.method == "GET":
data = []
# 生成模拟数据
for id in range(1, 15):
import random
# 随机生成姓
name = '姓' + random.choice(['风', '火', '雷', '电'])
# 随机生成性别
sex = random.choice(['男', '女'])
# 随机生成城市
city = random.choice(['北京', '上海', '深圳', '广州', '邯郸', '邱县'])
row = {'id': id, 'username': name, 'sex': sex, 'city': city}
# 根据查询关键字返回数据
search_key = request.GET.get('searchKey', None)
sexKey = request.GET.get('sexKey', None)
if search_key or sexKey:
# 使用 in 进行模糊查询
if search_key == name:
data.append(row)
elif sexKey == sex:
data.append(row)
else:
data.append(row)
# 分页
count = len(data)
page = int(request.GET.get('page', 1))
limit = int(request.GET.get('limit'))
start = (page - 1) * limit
end = page * limit
data = data[start:end]
code = "0"
msg = "获取数据成功"
result = {'code': code, 'msg': msg, 'count': count, 'data': data}
return JsonResponse(result)
if request.method == "POST":
print(request.POST)
code = '0'
msg = '删除成功'
result = {'code': code, 'msg': msg}
return JsonResponse(result)
DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>
{% block title %}
{% endblock %}
title>
<link rel="stylesheet" href="/static/layui/css/layui.css">
head>
<body>
{% block body_first %}
{% endblock %}
<div class="layui-layout layui-layout-admin">
<div class="layui-header layui-bg-cyan">
<div class="layui-logo layui-hide-xs layui-bg-black" style="font-size: 26px;">运维管理平台div>
<ul class="layui-nav layui-layout-left">
<li class="layui-nav-item layui-show-xs-inline-block layui-hide-sm" lay-header-event="menuLeft">
<i class="layui-icon layui-icon-spread-left">i>
li>
ul>
<ul class="layui-nav layui-layout-right">
<li class="layui-nav-item layui-hide layui-show-md-inline-block">
<a href="javascript:;">
<img src="//tva1.sinaimg.cn/crop.0.0.118.118.180/5db11ff4gw1e77d3nqrv8j203b03cweg.jpg"
class="layui-nav-img">
用户
a>
<dl class="layui-nav-child">
<dd><a href="">个人信息a>dd>
<dd><a href="">设置a>dd>
<dd><a href="">退出a>dd>
dl>
li>
<li class="layui-nav-item" lay-header-event="menuRight" lay-unselect>
<a href="javascript:;">
<i class="layui-icon layui-icon-more-vertical">i>
a>
li>
ul>
div>
<div class="layui-side layui-bg-black">
<div class="layui-side-scroll layui-bg-cyan">
<ul class="layui-nav layui-nav-tree layui-bg-cyan" lay-filter="test">
<li class="layui-nav-item layui-nav-itemed">
<a class="" href="javascript:;"><i
class="layui-icon layui-icon-face-smile">i> 其他系统a>
<dl class="layui-nav-child">
<dd><a href="javascript:;">OAa>dd>
<dd><a href="javascript:;">人事a>dd>
<dd><a href="javascript:;">考核a>dd>
<dd><a href="">the linksa>dd>
dl>
li>
<li class="layui-nav-item">
<a href="javascript:;">自动化a>
<dl class="layui-nav-child">
<dd><a href="javascript:;">CIa>dd>
<dd><a href="javascript:;">CDa>dd>
<dd><a href="">超链接a>dd>
dl>
li>
<li class="layui-nav-item"><a href="javascript:;">k8sa>li>
<li class="layui-nav-item"><a href="">邮箱系统a>li>
ul>
div>
div>
<div class="layui-body" style="background-color: #eeeeee;">
<div style="padding: 15px;">{% block content %}
{% endblock %}div>
div>
<div class="layui-footer">
底部固定区域www.test.com
div>
div>
<script src="/static/layui/layui.js">script>
{% block js %}
{% endblock %}
<script>
//JS
layui.use(['element', 'layer', 'util'], function () {
var element = layui.element
, layer = layui.layer
, util = layui.util
, $ = layui.$;
//头部事件
util.event('lay-header-event', {
//左侧菜单事件
menuLeft: function (othis) {
layer.msg('展开左侧菜单的操作', { icon: 0 });
}
, menuRight: function () {
layer.open({
type: 1
, content: '处理右侧面板的操作'
, area: ['260px', '100%']
, offset: 'rt' //右上角
, anim: 5
, shadeClose: true
});
}
});
});
script>
body>
html>
{% extends 'base.html' %}
{% block title %}
数据表格
{% endblock %}
{% block body_first %}
<div style="background-color: red;width: 100px;height: 100px;display: none;" id="abc">
页面层
div>
{% endblock %}
{% block content %}
{% csrf_token %}
<div class="layui-card">
<div class="layui-card-body">
<table id="demo" lay-filter="test">table>
<script type="text/html" id="toolbarDemo">
<!-- 搜索框 -->
<input type="text" name="username" class="layui-input" style="width: 150px;float: left;">
<button class="layui-btn" style="float: left;" id="searchBtn">搜索</button>
<!-- 直接选择或搜索选择 -->
<div class="layui-input-inline">
<select name="sex" lay-verify="required" lay-search="" lay-filter="sex">
<option value="">性别</option>
<option value="男">男</option>
<option value="女">女</option>
</select>
</div>
<br>
<br>
<!-- 头部按钮 -->
<!-- <div class="layui-btn-container">
<button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>
<button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>
<button class="layui-btn layui-btn-sm" lay-event="isAll">验证是否全选</button>
</div> -->
script>
<script type="text/html" id="barDemo">
<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
script>
div>
div>
<button tyle="submit" class="layui-btn" id="btn">弹出框button>
{% endblock %}
{% block js %}
<script>
layui.use(['layer', 'table', 'form'], function () {
var table = layui.table;
var layer = layui.layer;
var $ = layui.jquery;
var form = layui.form;
$("#btn").click(function () {
// layer.msg('hello',{icon:6})
// 信息框
/*
layer.open({
type: 0,
content: 'hello'
})
*/
// 页面层
/*
layer.open({
type: 1,
content: $('#abc')
})
*/
// 加载层
layer.open({
type: 2,
content: 'https://www.csdn.net/',
area: ['60%','50%'],
title: ["这是嵌套页面",'font-size:20px;color:red'],
btn: ['提交','关闭']
})
})
// 渲染表格
table.render({
elem: '#demo',
url: '/liebiao/',
title: '用户数据表',
toolbar: '#toolbarDemo', //开启头部工具栏,并为其绑定左侧模板
defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义,去除该参数即可
title: '提示'
, layEvent: 'LAYTABLE_TIPS'
, icon: 'layui-icon-tips'
}],
cols: [[
{ type: 'checkbox', fixed: 'left' },
{ field: 'id', title: 'ID', width: 80, fixed: 'left', unresize: true, sort: true },
{ field: 'username', title: '用户名', width: 120 },
{ field: 'sex', title: '性别', width: 120,templet: function (d) {
if (d.sex == "女") {
return '' + d.sex + ''
} else {
return '' + d.sex + ''
}
}},
{ field: 'city', title: '城市' },
{ fixed: 'right', title: '操作', toolbar: '#barDemo', width: 150 }
]],
page: true,
id: 'USER' // 表格的唯一标识,用于刷新
});
//头工具栏事件
table.on('toolbar(test)', function (obj) {
var checkStatus = table.checkStatus(obj.config.id);
switch (obj.event) {
case 'getCheckData':
var data = checkStatus.data;
layer.alert(JSON.stringify(data));
break;
case 'getCheckLength':
var data = checkStatus.data;
layer.msg('选中了:' + data.length + ' 个');
break;
case 'isAll':
layer.msg(checkStatus.isAll ? '全选' : '未全选');
break;
//自定义头工具栏右侧图标 - 提示
case 'LAYTABLE_TIPS':
layer.alert('这是工具栏右侧自定义的一个图标按钮');
break;
};
});
//监听行工具事件
table.on('tool(test)', function (obj) {
var data = obj.data;
//console.log(obj)
if (obj.event === 'del') {
layer.confirm('真的删除行么', function (index) {
// 执行删除操作
// obj.del();
// layer.close(index);
csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val()
var post_data = {
'id': data.id,
'csrfmiddlewaretoken': csrfmiddlewaretoken
}
$.ajax({
type: "POST",
url: "/liebiao/",
data: post_data,
success: function (result) {
if (result.code == "0") {
layer.msg(result.msg, { icon: 6 })
} else {
layer.msg(result.msg, { icon: 5 })
}
}
})
});
} else if (obj.event === 'edit') {
// 执行编辑操作
layer.prompt({
formType: 2
, value: data.email
}, function (value, index) {
obj.update({
email: value
});
layer.close(index);
});
}
});
// 搜索按钮点击事件
$(document).on('click', "#searchBtn", function () {
// $("#searchBtn").click(function () {
var input_val = $('input[name=username]').val();
// layer.msg(input_val)
// 重新加载表格数据,传递搜索关键字
table.reload('USER', {
where: {
searchKey: input_val
},
page: {
curr: 1
}
});
});
form.on('select(sex)', function (data) {
// $(document).on('click', "#sex", function () {
// var sex = $('input[sex=sex]').val();
table.reload('USER', {
where: { //设定异步数据接口的额外参数,任意设
sexKey: data.value,
},
page: {
curr: 1 //重新从第 1 页开始
}
}); //只重载数据
})
});
script>
{% endblock %}