【django小练习之主机管理界面】

需求:

利用django,js,bootstrap等实现登录,主机管理等操作。

实现截图

  • 登录界面

  • 主机界面,添加及编辑

  • 部门管理界面

代码实现

  • 目录层级

settings.py

"""
Django settings for day16 project.

Generated by ‘django-admin startproject‘ using Django 1.11.4.

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

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

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ‘l))&0*l6$aja*lcq8=0-s9u4byl2%alzfsgdxs_&3_qre&=mvw‘

# 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 = ‘day16.urls‘

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‘,
            ],
        },
    },
]

WSGI_APPLICATION = ‘day16.wsgi.application‘

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

DATABASES = {
    ‘default‘: {
        ‘ENGINE‘: ‘django.db.backends.sqlite3‘,
        ‘NAME‘: os.path.join(BASE_DIR, ‘db.sqlite3‘),
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.11/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/1.11/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/1.11/howto/static-files/

STATIC_URL = ‘/static/‘
STATICFILES_DIRS = (
    os.path.join(BASE_DIR,‘static‘),
)

settings.py

urls.py

"""day16 URL Configuration

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

urlpatterns = [
    url(r‘^admin/‘, admin.site.urls),
    url(r‘^login/‘,views.login),
    url(r‘^index/‘,views.index),
    url(r‘^parts/‘,views.parts),
    url(r‘^part_add/‘,views.part_add),
    url(r‘^part_del/‘,views.part_del),
    url(r‘^part_edit/‘,views.part_edit),
    url(r‘^hosts/‘,views.hosts),
    url(r‘^hosts_add/‘,views.hosts_add),
    url(r‘^hosts_del/‘,views.hosts_del),
    url(r‘^hosts_edit/‘,views.hosts_edit),

]

urls.py

models.py

from django.db import models

# Create your models here.
from django.db import models

class UserInfo(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.CharField(max_length=32)
    pwd = models.CharField(max_length=64)
    age = models.IntegerField()

class Department(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=32)

class Hosts(models.Model):
    id = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=64)
    ip = models.CharField(max_length=64)
    depart = models.ForeignKey(to=‘Department‘,to_field=‘id‘,default=1)

models.py

views.py

from django.shortcuts import render,HttpResponse,redirect

# Create your views here.

from app01 import models
# def test(request):
#     # #查询所有用户信息
#     # user_list = models.UserInfo.objects.all()
#     # for obj in user_list:
#     #     print(obj,obj.id,obj.user,obj.pwd)
#     #
#     # return HttpResponse(‘123‘)
#     #
#     # user_list = models.UserInfo.objects.filter(user=‘alex‘,pwd=‘123‘).all
#     # print(user_list)
#     #
#     # user = models.UserInfo.objects.filter(user=‘alex‘,pwd=‘123‘).first()
#     # print(user,user.id,user.user,user.pwd)
#     return HttpResponse(‘123‘)

def login(request):
    if request.method == "GET":
        #打开login.html文件
        #找到特殊标记{{msg}}
        #并将第三个参数中字典总的对应值替换
        #将替换完毕的字符串发送给用户浏览器
        return render(request,"login.html",{‘msg‘:‘‘})
    else:
        #去请求体中获取数据
        username1 = request.POST.get("username")
        password1 = request.POST.get("password")
        print(username1,password1)

        userinfo = models.UserInfo.objects.filter(user=username1,pwd=password1).first()
        print(userinfo)

        if userinfo:
            # return redirect(‘http://www.baidu.com‘)
            return redirect(‘/index/‘)
        else:
            return render(request,‘login.html‘,{‘msg‘:‘用户名或密码错误‘})

        # if user == "alex" and pwd == "123":
        #     #在响应头中设置,location:http://www.baidu.com,无响应体
        #     return redirect(‘http://www.baidu.com‘)
        #     #return redirect(‘/index/‘)
        # else:
        #     return render(request,‘login.html‘,{‘msg‘:‘用户名或密码错误‘})
def index(request):
    return render(request,‘index.html‘)

def parts(request):

    depart_list = models.Department.objects.all()

    return render(request,‘parts.html‘,{‘depart_list‘:depart_list})

def part_add(request):
    if request.method == ‘GET‘:
        return render(request,‘part_add.html‘)
    else:
        ti = request.POST.get(‘title‘)

        models.Department.objects.create(title=ti)

        return redirect(‘/parts/‘)

def part_del(request):
    nid = request.GET.get(‘nid‘)
    models.Department.objects.filter(id=nid).delete()
    return redirect(‘/parts/‘)

def part_edit(request):
    if request.method == ‘GET‘:
        nid = request.GET.get(‘nid‘)
        obj = models.Department.objects.filter(id=nid).first()

        if not obj:
            return HttpResponse(‘写错了,返回吧‘)
        return render(request,‘part_edit.html‘,{‘obj‘:obj})
    else:
        nid = request.GET.get(‘nid‘)
        title = request.POST.get(‘title‘)

        models.Department.objects.filter(id=nid).update(title=title)
        return redirect(‘/parts‘)

def hosts(request):

    hosts_list = models.Hosts.objects.all()

    return render(request,‘hosts.html‘,{‘hosts_list‘:hosts_list})

def hosts_add(request):
    if request.method == ‘GET‘:
        depart_list = models.Department.objects.all()
        return render(request,‘hosts_add.html‘,{‘depart_list‘:depart_list})
    else:
        hostname1 = request.POST.get(‘hostname‘)
        ip1 = request.POST.get(‘ip‘)
        dp_id = request.POST.get(‘dp_id‘)

        models.Hosts.objects.create(hostname=hostname1,ip=ip1,depart_id=dp_id)

        return redirect(‘/hosts‘)

def hosts_del(request):
    nid = request.GET.get(‘nid‘)
    models.Hosts.objects.filter(id=nid).delete()
    return redirect(‘/hosts‘)

def hosts_edit(request):
    if request.method == ‘GET‘:
        nid = request.GET.get(‘nid‘)
        obj = models.Hosts.objects.filter(id=nid).first()
        depart_list = models.Department.objects.all()

        if not obj:
            return HttpResponse(‘写错了,返回吧‘)
        return render(request,‘hosts_edit.html‘,{‘obj‘:obj,‘depart_list‘:depart_list})
    else:
        nid = request.GET.get(‘nid‘)
        hostname1 = request.POST.get(‘hostname‘)
        ip1 = request.POST.get(‘ip‘)
        dp_id = request.POST.get(‘dp_id‘)

        models.Hosts.objects.filter(id=nid).update(hostname=hostname1,ip=ip1,depart_id=dp_id)
        return redirect(‘/hosts‘)

views.py

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/plugins/bootstrap/css/bootstrap.css">
</head>
<body>

<div style="width: 500px;margin: 0 auto;margin-top: 80px;">
    <h2>登录界面</h2>
    <form class="form-horizontal" action="/login/" method="post">
        <div class="form-group">
            <label for="n1" class="col-sm-2 control-label">用户名</label>
            <div class="col-sm-10">
                <input id="n1" type="text" name="username" class="form-control" placeholder="用户名">
            </div>
        </div>
        <div class="form-group">
            <label for="n2" class="col-sm-2 control-label">密码</label>
            <div class="col-sm-10">
                <input id="n2" type="password" name="password" class="form-control" placeholder="密码">
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <input type="submit" value="登 录" class="btn btn-primary">{{ msg }}
            </div>
        </div>
    </form>
</div>
</body>
</html>

login.html

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/plugins/bootstrap/css/bootstrap.css">
</head>
<body>
 <h2 style="width: 500px;margin-top: 10px;margin-left:50px; ">欢迎登录</h2>
<div style="width: 500px;margin-top: 30px;margin-left:100px; ">

    <ul class="list-unstyled">
        <li style="font-size: larger;"><a href="/parts/"><span class="glyphicon glyphicon-star" aria-hidden="true"></span>业务线管理</a></li>
        <li style="font-size: larger;"><a href="/hosts/"><span class="glyphicon glyphicon-star" aria-hidden="true"></span>主机管理</a></li>

    </ul>
</div>
</body>
</html>

index.html

parts.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/plugins/bootstrap/css/bootstrap.css">
</head>
<body>
    <div class="container">
        <h1>部门列表</h1>
        <div style="margin: 5px 0">
            <a href="/part_add/" class="btn btn-success"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span>添加</a>
        </div>
        <table class="table table-bordered">
            <thead>
                <tr class="info">
                    <th>ID</th>
                    <th>部门</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                {% for obj in depart_list %}
                    <tr>
                        <td>{{ obj.id }}</td>
                        <td>{{ obj.title }}</td>
                        <td>
                            <a href="/part_edit/?nid={{ obj.id }}" class="btn btn-info"><span class="glyphicon glyphicon-cog" aria-hidden="true"></span>编辑</a>
                            <a href="/part_del/?nid={{ obj.id }}" class="btn btn-danger"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除</a>
                        </td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>

</body>
</html>

parts.html

parts_add.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/plugins/bootstrap/css/bootstrap.css">
</head>
<body>

<div style="width: 500px;margin: 0 auto;margin-top: 80px;">
    <h2>添加部门</h2>
    <form class="form-horizontal" action="" method="post">
        <div class="form-group">
            <label for="n1" class="col-sm-2 control-label">部门名称</label>
            <div class="col-sm-10">
                <input  type="text" name="title" class="form-control" >
            </div>
        </div>

        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <input type="submit" value="添加" class="btn btn-primary">
            </div>
        </div>
    </form>
</div>
</body>
</html>

parts_add.html

parts_edit.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/plugins/bootstrap/css/bootstrap.css">
</head>
<body>

<div style="width: 500px;margin: 0 auto;margin-top: 80px;">
    <h2>编辑部门</h2>
    <form class="form-horizontal" action="" method="post">
        <div class="form-group">
            <label for="n1" class="col-sm-2 control-label">部门名称</label>
            <div class="col-sm-10">
                <input  type="text" name="title" class="form-control" value="{{ obj.title }}">
            </div>
        </div>

        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <input type="submit" value="修改" class="btn btn-default">
            </div>
        </div>
    </form>
</div>
</body>
</html>

parts_edit.html

hosts.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/plugins/bootstrap/css/bootstrap.css">
</head>
<body>
    <div class="container">
        <h1>主机列表</h1>
        <div style="margin: 5px 0">
            <a href="/hosts_add/" class="btn btn-success"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span>添加</a>
        </div>
        <table class="table table-bordered">
            <thead>
                <tr class="info">
                    <th>ID</th>
                    <th>主机名</th>
                    <th>ip</th>
                    <th>部门id</th>
                    <th>所属部门</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                {% for obj in hosts_list %}
                    <tr>
                        <td>{{ obj.id }}</td>
                        <td>{{ obj.hostname }}</td>
                        <td>{{ obj.ip}}</td>
                        <td>{{ obj.depart_id}}</td>
                        <td>{{ obj.depart.title }}</td>
                        <td>
                            <a href="/hosts_edit/?nid={{ obj.id }}" class="btn btn-info"><span class="glyphicon glyphicon-cog" aria-hidden="true"></span>编辑</a>
                            <a href="/hosts_del/?nid={{ obj.id }}" class="btn btn-danger"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除</a>
                        </td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>

</body>
</html>

hosts.html

hosts_add.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/plugins/bootstrap/css/bootstrap.css">
</head>
<body>

<div style="width: 500px;margin: 0 auto;margin-top: 80px;">
    <h2>添加主机</h2>
    <form class="form-horizontal" action="" method="post">
        <div class="form-group">
            <label for="n1" class="col-sm-2 control-label">主机名</label>
            <div class="col-sm-10">
                <input  type="text" name="hostname" class="form-control" >
            </div>
        </div>
        <div class="form-group">
            <label for="n2" class="col-sm-2 control-label">ip</label>
            <div class="col-sm-10">
                <input id="n2" type="text" name="ip" class="form-control" >
            </div>
        </div>
        <div class="form-group">
            <label for="n3" class="col-sm-2 control-label">所属部门</label>
            <div class="col-sm-10">
                <select name=‘dp_id‘ class="form-control">
                    {% for x in depart_list %}
                        <option value="{{x.id}}">{{x.title}}</option>
                    {% endfor%}
                </select>
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <input type="submit" value="添加" class="btn btn-primary">
            </div>
        </div>
    </form>
</div>
</body>
</html>

hosts_add.html

hosts_edit.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/plugins/bootstrap/css/bootstrap.css">
</head>
<body>

<div style="width: 500px;margin: 0 auto;margin-top: 80px;">
    <h2>编辑主机信息</h2>
    <form class="form-horizontal" action="" method="post">
        <div class="form-group">
            <label for="n1" class="col-sm-2 control-label">主机名</label>
            <div class="col-sm-10">
                <input  type="text" name="hostname" class="form-control" value="{{ obj.hostname }}">
            </div>
        </div>

        <div class="form-group">
            <label for="n2" class="col-sm-2 control-label">ip</label>
            <div class="col-sm-10">
                <input  type="text" name="ip" class="form-control" value="{{ obj.ip }}">
            </div>
        </div>

        <div class="form-group">
            <label for="n3" class="col-sm-2 control-label">所属部门</label>
            <div class="col-sm-10">
                <select name=‘dp_id‘>
                    {% for x in depart_list %}
                        <option value="{{x.id}}" selected>{{x.title}}</option>
                    {% endfor%}
                </select>
            </div>
        </div>

        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <input type="submit" value="修改" class="btn btn-default">
            </div>
        </div>
    </form>
</div>
</body>
</html>

hosts_edit.html

原文地址:https://www.cnblogs.com/smallmars/p/8353507.html

时间: 2024-07-31 02:45:10

【django小练习之主机管理界面】的相关文章

小贝_redis web管理界面工具安装

RedisWEB管理界面工具安装 一.概述 二.文件下载 三.安装过程 一.概述 1.因为redis是基于C/S的方式开发.也就是说,仅仅要满足于redis的client通信要求的,都能够作为redis的client,进行连接服务端进行管理操作.这里採用的是基于web方式的来管理redis. 2.基于web的方式的优缺点: 2.1.长处: a.在client这边不须要多余操作.仅仅需有个浏览器就可以 2.2.缺点: a.因为是web方式,因此,须要server提供web服务,假设web服务配置不

一个简单的主机管理模拟程序

最近写的一个小练习,主要是把前面学的东西整合一下.写了一个简单的主机管理界面,主要是练习以下知识点: Session和Cookie进行登录验证(装饰器) 数据库的基本操作 (单表,1对多,多对多) Form的简单使用实现验证 Bootstrap模板写个简单界面 自定义分页 信号,中间件,CSRF,模板语言,JavaScript,AJAX等等 界面比较low,毕竟不是专业的. 附件里面是Django的源代码,3个文件放在一起winrar解压就可以打开

Django后台管理界面

之前的几篇记录了模板视图.模型等页面展示的相关内容,这篇主要写一下后台admin管理界面的内容. 激活管理界面 Django管理站点完全是可选择的,之前我们是把这些功能给屏蔽掉了.记得上篇中Django模型模型安装小结中,我们把settings.py中的部分内容屏蔽了,并添加了一个app,如下 1 INSTALLED_APPS = ( 2 ## 'django.contrib.admin', 3 ## 'django.contrib.auth', 4 ## 'django.contrib.con

django简单实现项目和app的创建,并通过admin管理界面管理

一.先实现admin管理界面的访问 1.先创建项目 [email protected]:~/Django-1.5.12/django/bin# django-admin.py startproject justplay [email protected]:~/Django-1.5.12/django/bin/justplay# ls just  justplay  manage.py 2.创建app [email protected]:~/Django-1.5.12/django/bin/jum

Django + Ansible 主机管理

本文分享内容如下: 内容目录 Django 基础 MVC ORM COMMAND AuthenticationAnsible 基础 配置 ad-hoc 命令集 python api代码解读 演示 创建虚拟化环境并进入python3/python -m venv venv(linux)source venv\bin\active(win) venv\Scripts\active 安装第三方库pip install -r requirements.txt 初始化python manage.py ma

frist Django app— 二、 Model和管理界面

Django是符合MVC架构的,这里现学习M—Model,而且Django自带了一个管理model(数据库)的界面,所以一并学习. Database 配置 编辑Django的配置文件settings.py进行配置 添加polls app,修改后如下 INSTALLED_APPS = [ 'django.contrib.admin', # 管理界面 'django.contrib.auth', # 认证系统 'django.contrib.contenttypes', # 框架的content t

Django 之管理界面

     为新增的books应用开启管理界面 1.项目/setting.py文件的修改 (a) 将'django.contrib.admin'加入setting的INSTALLED_APPS配置中 (默认已经有.INSTALLED_APPS中的配置顺序是没有关系的) (b). 保证INSTALLED_APPS中包 含'django.contrib.auth','django.contrib.contenttypes'和'django.contrib.sessions', Django的管理工具需

解决Django Admin管理界面样式表(CSS Style)丢失问题

我在配置django自带管理界面过程中登录http://domain.com/admin后台时出现样式表丢失的问题,界面变成了这样: 系统环境:centos6.5+nginx1.5.9+uwsgi2.0.4+django1.4.9 nginx配置文件: server {         listen       80;         server_name  www.omserver.com;         location / {             uwsgi_pass 192.16

day17 Django 主机管理

s19day17 内容回顾: 1. jQuery - 选择 - 操作 - 事件 2. Http协议 - 3. Django框架 版本:1.11 创建: django-admin startprojcet xxx cd xxx python manage.py startapp app01 python manage.py runserver 127.0.0.1:8000 今日内容: 1. 请求生命周期 2. 主机管理 - 路由系统 - 视图函数 - ORM(操作数据库) - 模板 内容详细: 1