文章目录
- 功能
- 涉及知识点
- 配置
- 代码
- 路由系统相关
- 数据库相关
- 视图系统相关
- 模板系统相关
- git 地址
功能
- 对主机进行信息录入, 包括主机名和 IP 地址
- 能对主机进行增删改查
涉及知识点
- 路由系统
- path, re_path, include 模块的使用
- url, get 请求传参( www.xxx.com/api/?id=xxx )
- url, 位置传参
- 视图系统
- FBV 和 CBV
- 别名和 reverse 的用法
- 模板系统
- 母版
- ORM
- 单表的增删改查
配置
- settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 下边两行是自己添加的
'host.apps.HostConfig',
"index.apps.IndexConfig",
]
# 403 报错需要注释一个中间件
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',
]
# 静态文件存放的路径别名, 并非是存放路径
STATIC_URL = '/static/'
# 实际存放路径, 存放 css, js等
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
代码
路由系统相关
- 总 urls.py
from django.contrib import admin
from django.urls import path, re_path, include
from index import views as index_views
from host import urls as host_urls
urlpatterns = [
path('admin/', admin.site.urls),
path("index/", index_views.index),
re_path(r"^host/", include(host_urls))
]
- host/urls.py
from django.urls import path, re_path
from host import views
urlpatterns = [
path('list/', views.host_list, name="host_list"),
path('add/', views.Host_add.as_view()),
re_path(r'del/(\d+)', views.host_del),
path("edit/", views.Host_edit.as_view()),
]
数据库相关
- host/models.py
from django.db import models
# Create your models here.
class Host(models.Model):
# AutoField 表示自增列
# primary_key 表示为该表主键
id = models.AutoField(primary_key=True)
hostname = models.CharField(max_length=16)
ip_addr = models.CharField(max_length=32)
视图系统相关
- index/views.py
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, "index.html")
- host/views.py
from django.shortcuts import render, redirect, HttpResponse
from django import views
from host import models
from django.urls import reverse
# Create your views here.
def host_list(request):
# 查询 Host 表下所有的数据
data = models.Host.objects.all()
return render(request, "host_list.html", {"data": data})
class Host_add(views.View):
def get(self, request):
# 直接返回页面
return render(request, "host_add.html")
def post(self, request):
# 获取前端页面中 form 表单中 name 属性的数据
hostname = request.POST.get("hostname")
ip_addr = request.POST.get("ip_addr")
models.Host.objects.create(hostname=hostname, ip_addr=ip_addr)
return redirect(reverse("host_list"))
class Host_edit(views.View):
def get(self, request):
# 从 get 请求中拿到 id 的值
host_id = request.GET.get("id")
# 根据 id 查询, 可以使用 get 和 filter
data = models.Host.objects.filter(id=host_id)
# 做了一个容错
if len(data) == 0 or len(data) > 1:
return HttpResponse("数据查询出错")
else:
return render(request, "host_edit.html", {"data": data[0]})
def post(self, request):
# 从前端获取新数据
hostname = request.POST.get("hostname")
ip_addr = request.POST.get("ip_addr")
# 在 list 界面拼接了 url, id 作为 get 请求的参数
# 根据 id 拿到对应的数据库对象
host_id = request.GET.get("id")
obj = models.Host.objects.filter(id=host_id)[0]
# 修改数据为新的值
obj.hostname = hostname
obj.ip_addr = ip_addr
# 保存
obj.save()
return redirect(reverse("host_list"))
def host_del(request, id):
# 找到数据库对象, 并且调用 delete() 删除它
models.Host.objects.filter(id=id).delete()
return redirect(reverse("host_list"))
模板系统相关
- 总 templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>
{% block page_title %}
{# 标题的位置 #}
{% endblock %}
</title>
<link href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
{% block page_css %}
{# 单页面引入 css 文件位置 #}
{% endblock %}
</head>
<body>
<div class="container-fluid">
<div class="row" style="margin-top: 70px">
{% block page_main %}
{# 页面代码位置 #}
{% endblock %}
</div>
</div>
<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
<script src="/static/jquery/jquery-3.5.1.min.js"></script>
<!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
<script src="/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
{% block page_js %}
{# 单页面引入 js 文件位置 #}
{% endblock %}
</body>
</html>
- 总 templates/index.html
{#引入母版文件#}
{% extends "base.html" %}
{% block page_title %}
主页
{% endblock %}
{% block page_main %}
<a href="/host/list/">主机列表</a>
{% endblock %}
- host/host_list.html
{% extends "base.html" %}
{% block page_title %}
主机列表
{% endblock %}
{% block page_main %}
<div class="col-md-6 col-md-offset-3">
<h2>主机列表</h2>
<a href="/host/add/" methods="get" class="btn btn-default" style="float: right">添加新的主机</a>
<table class="table table-hover">
<thead>
<tr>
<th>序号</th>
<th>HostName</th>
<th>IP地址</th>
<th>操作</th>
</tr>
</thead>
{# 按照 Django 的特殊语法 写特殊符号, 替换数据 #}
<tbody>
{% for i in data %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ i.hostname }}</td>
<td>{{ i.ip_addr }}</td>
<td><a href="/host/edit/?id={{ i.id }}" class="btn btn-warning">编辑</a> <a href="/host/del/{{ i.id }}" class="btn btn-danger">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
- host/host_add.html
{% extends "base.html" %}
{% block page_title %}
添加主机
{% endblock %}
{% block page_main %}
<div class="col-md-3 col-md-offset-4">
<h2>添加主机</h2>
<form action="" method="post">
<div class="form-group">
<label for="hostname">hostname</label>
<input type="text" class="form-control" id="hostname" name="hostname" placeholder="hostname">
</div>
<div class="form-group">
<label for="ip_addr">ip_addr</label>
<input type="text" class="form-control" id="ip_addr" name="ip_addr" placeholder="ip_addr">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
{% endblock %}
- host/host_edit.html
{% extends "base.html" %}
{% block page_title %}
编辑主机
{% endblock %}
{% block page_main %}
<div class="col-md-3 col-md-offset-4">
<h2>编辑主机</h2>
<form action="" method="post">
<div class="form-group">
<label for="hostname">hostname</label>
<input type="text" class="form-control" id="hostname" name="hostname" placeholder="hostname" value="{{ data.hostname }}">
</div>
<div class="form-group">
<label for="ip_addr">ip_addr</label>
<input type="text" class="form-control" id="ip_addr" name="ip_addr" placeholder="ip_addr" value="{{ data.ip_addr }}">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
{% endblock %}
git 地址
git clone git@code.aliyun.com:KAY/django.Host_Manager_1.git