项目创建及准备

创建

# 创建项目
django-admin startproject MPlat
# 创建app
python manage.py startapp machine

# 设置
# 1.安装app
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'machine',
]
# 2.allowed_hosts
ALLOWED_HOSTS = ['*']
# 3.templates_dir,并在路径下创建templates文件夹,及machine文件夹
'DIRS': [os.path.join(BASE_DIR,'templates')],
# 4.注释掉csrf
#'django.middleware.csrf.CsrfViewMiddleware',
# 5.汉化
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'

数据库配置使用mysql

在数据库创建mplat

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mplat',
        'USER': 'root',
        'PASSWORD':'root',
        'HOST':'192.168.1.3',
        'PORT':'3306',
    }
}

# 初始化数据库
python manage.py migrate

后台密码创建

python manage.py createsuperuser

模型设计及创建

user表

字段名 类型 长度 备注
usernum char 64 用户账号
passwd char 64 用户密码
username char 64 用户昵称

machine表

字段名 类型 长度 备注
ip char 15 ip地址
user_id foreiginkey 指向用户id
asset_num char 64 资产编号
device_location char 64 机柜位置
os char 64 操作系统
create_time time 创建时间
update_time time 更新时间

models表

from django.db import models

# Create your models here.
class User(models.Model):
    class Meta:
        db_table = 'user'

    usernum = models.CharField(max_length=64,db_column='usernum')
    passwd = models.CharField(max_length=64,db_column='passwd')
    username = models.CharField(max_length=64,db_column='username')


class Machine(models.Model):
    class Meta:
        db_table = 'machine'

    ip = models.CharField(max_length=15,db_column='ip')
    user_id = models.ForeignKey(User,db_column='user_id',on_delete=models.CASCADE)
    asset_num = models.CharField(max_length=64, db_column='asset_num')
    device_location = models.CharField(max_length=64, db_column='device_location')
    os = models.CharField(max_length=64, db_column='os')
    create_time = models.DateTimeField(db_column='create_time')
    update_time = models.DateTimeField(db_column='update_time')

admin

from django.contrib import admin

# Register your models here.
from machine.models import *

class UserInfoAdmin(admin.ModelAdmin):

    list_display = ['id','usernum','passwd','username']

class MachineInfoAdmin(admin.ModelAdmin):

    list_display = ['ip','user_id','asset_num','device_location','create_time','update_time']

admin.site.register(User,UserInfoAdmin)
admin.site.register(Machine,MachineInfoAdmin)
python manage.py makemigrations
python manage.py migrate	

增加账号

增加两个账号密码 ming 和 hong

登陆功能

路径准备

根目录下的urls
from django.contrib import admin
from django.urls import path
from django.conf.urls import include,url

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^',include('machine.urls',namespace='machine')),
]
machine下的url
from django.conf.urls import url

from machine import views

app_name = 'machine'
urlpatterns = [
    url(r'^$',views.index,name='index'),
]
view
def index(request):
    return render(request,'index.html',{})
index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
这是登陆界面
</body>
</html>

登陆页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/static/layui/css/layui.css" media="all">
    <title>登录界面</title>
</head>
<body>
<style type="text/css">
    body {
        background-image: url(/static/images/login-bg.jpg);
    }
</style>
<div class="layui-col-xs6">
    <div class="grid-demo">&nbsp;</div>
</div>
<div class="layui-col-xs6" style="padding-top: 15%;">
    <div style="width:50%;margin:0 auto;text-align: center">
        <form class="layui-form" method="POST" action="login">
            <div class="layui-form-item" style="margin:0 auto">
                <div class="layui-input-inline">
                    用户登录<br><br>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-inline">
                    <input type="text" name="title" required lay-verify="required" placeholder="请输入账号"
                           autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-inline">
                    <input type="password" name="password" required lay-verify="required" placeholder="请输入密码"
                           autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item" style="margin:0 auto">
                <div class="layui-input-inline">
                    <button class="layui-btn" lay-submit lay-filter="formDemo" style="padding:0 42%">登录</button>
                </div>
            </div>
        </form>
    </div>
</div>

<script src="/static/layui/layui.all.js" type="text/javascript" charset="utf-8"></script>
<script>
    layui.use('form', function () {
        var form = layui.form;
        //监听提交
        form.on('submit(formDemo)', function (data) {
            layer.msg(JSON.stringify(data.field));
            
            return false;
        });
    });
</script>

</body>
</html>

到这一步,我们简单登陆页面就写完了。我们接下来要继续完成,登陆界面的功能。

比如我点击登陆后,我们要进行账号密码的校验及校验完成后的跳转。我们先简单顶一个跳转页面。在模板下创建文件。

def machine(request):
    return render(request,'machine/machine.html',{})
urlpatterns = [
    url(r'^$',views.index,name='index'),
    url(r'^machine',views.machine,name='machine'),
]
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
这是机器展示页面
</body>
</html>

登陆的接口

这里我们需要定义登录的接口。login

url(r'^login$',views.login,name='login')
from django.http import JsonResponse


def login(request):
    return JsonResponse({})

我们在index,html中使用jquery,将登陆信息传到后台,进行登陆校验,校验通过返回1,前端接收到1后进行跳转,跳转到指定的页面。

import json
from machine.models import *

def login(request):
    field = request.POST.get('field')
    field = json.loads(field)
    usernum = field['usernum']
    password = field['password']

    # 和数据库中的对比,检查是否正确
    obj = User.objects.filter(usernum=usernum)
    if len(obj) == 0:
        return JsonResponse({'message':0})
    elif obj[0].passwd != password:
        return JsonResponse({'message':0})
    else:
        return JsonResponse({'message':1})
<script src="/static/jquery-1.12.4.min.js" type="text/javascript" charset="utf-8"></script>
<script>
    layui.use('form', function () {
        var form = layui.form;
        //监听提交
        form.on('submit(formDemo)', function (data) {
            //layer.msg(JSON.stringify(data.field));
            var field = JSON.stringify(data.field)
               $.post(
                           '{% url 'machine:login' %}',
                           {
                               field:field,
                            },
                           function (data) {//修改成功后需要关闭弹窗并且重载表格
                               if (data.message == 1){
                                   layer.msg('登录成功', {icon: 1,time:1000})
                                     setTimeout(function(){window.location.href = 'machine';},1000)
                               }else if (data.message == 0){
                                   layer.msg('用户名或者密码错误', {icon: 5,time:1000})
                               }
                           }
               )
            return false;
        });
    });
</script>

机器管理页面

框架搭建

机器管理页面就是我们的核心页面。由登陆跳转到这里后,直接展示我们的机器管理平台。

先从layui首页复制过来,看看它的样子

def home(request):
    return render(request,'home.html',{})

url(r'^home$',views.home,name='home')

删除掉部分内容,发现主体框架没有移动过去,故修改之。添加父类模板标签

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title>MPlat</title>
  <link rel="stylesheet" href="/static/layui/css/layui.css">
</head>
<body class="layui-layout-body">
<div class="layui-layout layui-layout-admin">
  <div class="layui-header">
    <div class="layui-logo">MPlat</div>
    <!-- 头部区域(可配合layui已有的水平导航) -->
    <ul class="layui-nav layui-layout-left">
      <li class="layui-nav-item"><a href="">控制台</a></li>
    </ul>
    <ul class="layui-nav layui-layout-right">
      <li class="layui-nav-item">
        <a href="javascript:;">
          <img src="http://t.cn/RCzsdCq" class="layui-nav-img">
          贤心
        </a>
        <dl class="layui-nav-child">
          <dd><a href="">基本资料</a></dd>
          <dd><a href="">安全设置</a></dd>
        </dl>
      </li>
      <li class="layui-nav-item"><a href="">退出</a></li>
    </ul>
  </div>

  <div class="layui-body" style="left: 15px ; right:0px">
    {% block home%}
      {% endblock home%}

  </div>

  <div class="layui-footer" style="left: 0px;">
    <!-- 底部固定区域 -->
    © MPlat.com
  </div>
</div>
</body>
</html>
{% extends 'home.html'%}
{%block home%}
这是机器界面
{%endblock home%}
MPlat.zip