19周 11章 django ORM基本创建类型以及生成数据库结构
类型:
dbfirst :通过数据库创建类
codefirst:先创建类 再创建数据库 --最常用
ORM的意思: 通过类创建数据库
对数据库操作步骤如下:
1、默认链接 sqlite 如果要链接mysql 需要进行配置:
前提:需要创建mysql数据库:dbname
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME':'dbname',
'USER': 'root',
'PASSWORD': 'xxx',
'HOST': '192.168.0.92',
'PORT': '',
}
}
2、在project同名文件夹的__init__文件中添加如下代码:
import pymysql
pymysql.install_as_MySQLdb()
3、admin后台注册表,admin内容如下:
from django.contrib import admin
from app01 import models
admin.site.register(models.UserInfo)
# Register your models here.
4、配置pycharm环境变量
4.1、Run --> EditConfigures
4.2、里面所有文件点开,修改里面的Environment variables 添加一项。
名称是DJANGO_SETTINGS_MODULE 值是settings.py文件所在的目录名称,比如 untitled4.settings
如果没有配置pycharm环境变量,是无法写入数据库中数据的,而且单个运行views.py会报如下错误:
django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not configured.
You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings
5、创建model表,根据类自动创建数据表
from django.db import models
class UserInfo(models.Model):
#自动创建 id列 自增主键
username=models.CharField(max_length=32)
password=models.CharField(max_length=64)
6、生成相应的表,执行命令:
python manage.py makemigrations
python manage.py migrate
直接结果如下:
[root@test3 project]# python manage.py makemigrations
Migrations for 'app02':
app02/migrations/0001_initial.py
- Create model UserInfo
[root@test3 project]# python manage.py migrate
Operations to perform:
Apply all migrations: admin, app02, auth, contenttypes, sessions
Running migrations:
Applying app02.0001_initial... OK
7、在views.py中定义对数据进行增删改查,models.py内容如下:
from app01 import models
def orm(request):
models.UserInfo.objects.create(username='root', password='', )
obj = models.UserInfo(username='bob', password='')
obj.save()
8、测试
先单个执行urls.py、models.py、views.py 如果报错就对照错误排错把,否则运行了项目也无法写入到数据库
19周 13章 django ORM 基本操作 增、删、改、查
1、先导入模块
from app01 import models
创建
models.UserInfo.objects.create(username='root',password='',)
obj=models.UserInfo(username='bob',password='')
obj.save()
dic={'username':'jack','password':''}
models.UserInfo.objects.create(dic)
查
result=models.UserInfo.objects.all()
result=models.UserInfo.objects.filter(username='root',password=999)
拿到的是一个对象,而且是名字、密码都一样的第一个
obj=models.UserInfo.objects.filter(username=u,password=p).first()
取对象中的某一个数据
obj=models.UserInfo.objects.filter(id=3).first()
print(obj.username)
拿到的是一个列表,而且是名字、密码都一样的多个
obj=models.UserInfo.objects.filter(username=u,password=p)
循环拿列表中的某一个数据:
def orm(request):
obj=models.UserInfo.objects.filter(id=3)
for i in obj:
print(i.username)
return HttpResponse('orm')
删除:
models.UserInfo.objects.filter().delete()
更新
models.UserInfo.objects.all().update(password=888)
models.UserInfo.objects.filter(id=1).update(password=999
第19章\urls.py
urlpatterns = [
url(r'^cmdb/',include("app01.urls")),
url(r'^monitor/',include("app02.urls")),
]
app01\views.py
from app01 import models
def orm(request):
创建
models.UserInfo.objects.create(username='root',password='',)
obj=models.UserInfo(username='bob',password='')
obj.save()
dic={'username':'jack','password':''}
models.UserInfo.objects.create(dic)
查
result=models.UserInfo.objects.all()
result=models.UserInfo.objects.filter(username='root',password=999)
删除:
models.UserInfo.objects.filter().delete()
更新
models.UserInfo.objects.all().update(password=888)
models.UserInfo.objects.filter(id=1).update(password=999
第19章 14节 基于ORM实现用户登录:
报错问题:
1、访问页面没有内容,返回200错误,说明肯定是html里面的内容写错了
2、ValueError: not enough values to unpack (expected 2, got 1)
这个错误说明:obj=models.UserInfo.objects.filter(id=nid).first() 这个里面没有写“id=”
或者:{'obj':obj} 这个写错了
总之是括号里面的少个东西
3、url一定要写成这样格式,否则很容易报错
url(r'^userdetail-(?P<nid>\d+)/', views.user_detail,),
ORM实例:
app01/urls.py内容如下:
"""第19章 URL Configuration
from django.contrib import admin
from django.urls import path
from app01 import views
from django.conf.urls import url
urlpatterns = [
path('login/', views.login),
path('index/', views.index,),
path('user_info/', views.user_info,),
url(r'^userdetail-(?P<nid>\d+)/', views.user_detail,),
path('orm/', views.orm),
]
app01/views.py内容如下:
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.shortcuts import redirect
import urllib
# Create your views here.
# USER_DICT={
# 'k1':'root1',
# 'k2':'root2',
# 'k3':'root3',
# 'k4':'root4',
# }
USER_DICT={
'1':{'name':'root1','email':'root@123.com'},
'2':{'name':'root2','email':'root@123.com'},
'3':{'name':'root3','email':'root@123.com'},
'4':{'name':'root4','email':'root@123.com'}
}
def index(request):
return render(request,'index.html')
def user_info(request):
user_list=models.UserInfo.objects.all()
#print(user_list.query)
return render(request,'user_info.html',{'user_list':user_list})
def user_detail(request,nid):
obj=models.UserInfo.objects.filter(id=nid).first()
return render(request,'user_detail.html',{'obj':obj})
def login(request):
if request.method=="GET":
return render(request,'login.html')
elif request.method=="POST":
#数据库中执行 select 判断用户名和密码是否中确
u=request.POST.get('user')
p=request.POST.get('pwd')
#count=models.UserInfo.objects.filter(username=u,password=p).count() 也可以,但是不经常用
obj=models.UserInfo.objects.filter(username=u, password=p).first()
#print(obj)
#下面意思:如果obj为真
if obj:
return redirect('/cmdb/index/')
else:
return render(request,'login.html')
else:
return redirect('/index/')
from app01 import models
def orm(request):
#创建
#models.UserInfo.objects.create(username='root',password='123',)
# obj=models.UserInfo(username='bob',password='456')
# obj.save()
# dic={'username':'jack','password':'789'}
# models.UserInfo.objects.create(dic)
#查
result=models.UserInfo.objects.all()
#result=models.UserInfo.objects.filter(username='root',password=999)
#
#删除:
#models.UserInfo.objects.filter().delete()
#更新
#models.UserInfo.objects.all().update(password=888)
# obj=models.UserInfo.objects.filter(id=3)
# for i in obj:
# print(i.username)
#
return HttpResponse('orm')
# from django.views import View
#
# class Home(View):
# def dispatch(self, request, *args, **kwargs):
# print('before')#kkkk
# result=super(Home,self).dispatch(request, *args, **kwargs)
# print('after')
# return result
#
# def get(self,request):
# print(request.method)
# return render(request,'home.html')
# def post(self,request):
# print(request.method)
# return render(request,'home.html')
templates/login.html内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body >
<form action="/cmdb/login/" method="POST" enctype="multipart/form-data">
<p>
<input type="text" name="user" placeholder="用户名">
</p>
<p>
<input type="password" name="pwd" placeholder="密码">
</p>
<input type="submit" value="提交">
</form>
</body>
</html>
templates/index.html内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
margin: 0;
}
.menu{
display: block;
padding: 5px;
}
</style>
</head>
<body>
<div style="height: 48px;background-color: black;color: white">
欢迎到来
</div>
<div>
<div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine">
<a class="menu" href="/cmdb/user_info/">用户管理</a>
<a class="menu" href="/cmdb/user_group/">用户组管理</a>
</div>
</div>
<div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 0;overflow: auto">
</div>
</body>
</html>
templates/user_info.html内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
margin: 0;
}
.menu{
display: block;
padding: 5px;
}
</style>
</head>
<body>
<div style="height: 48px;background-color: black;color: white">
欢迎到来
</div>
<div>
<div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine">
<a class="menu" href="/cmdb/user_info/">用户管理</a>
<a class="menu" href="/cmdb/user_group/">用户组管理</a>
</div>
</div>
<div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 700px;overflow: auto;background-color: antiquewhite">
<h3>用户列表</h3>
<ul>
{% for row in user_list %}
<li><a href="/cmdb/userdetail-{{ row.id }}/">{{ row.username }}</a></li>
{% endfor %}
</ul>
</div>
</body>
</html>
templates/user_detail.html内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
margin: 0;
}
.menu{
display: block;
padding: 5px;
}
</style>
</head>
<body>
<div style="height: 48px;background-color: black;color: white">
欢迎到来
</div>
<div>
<div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine">
<a class="menu" href="/cmdb/user_info/">用户管理</a>
<a class="menu" href="/cmdb/user_group/">用户组管理</a>
</div>
</div>
<div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 700px;overflow: auto;background-color: antiquewhite">
<h1>用户详细信息</h1>
<h2>{{ obj.id }}</h2>
<h2>{{ obj.name }}</h2>
<h2>{{ obj.password }}</h2>
</div>
</body>
</html>
19周-15章python基于 Django 基于ORM实现用户增加、删除、修改、查看
models.Business.objects.all()
是个对象
models.Business.objects.values('id','caption')
#[{'id':'1','caption':'运维','code':'sa'}] values 是个字典
models.Business.objects.values_list('id','caption')
#[(1,运维),(2,市场)] values_list 是个元组
1、
注意:method="post" 一定要写。一定是小写 否则报错
<form action="/cmdb/user_info/" method="post">
2、
注意href和action、return redirect三个的区分,容易混淆
这是做的跳转:
<a class="menu" href="/cmdb/user_info/">用户管理</a>
这是提交的当前的页面:
<form method="post" action="/cmdb/useredit-{{ obj.id }}/">
这个不加html
return redirect用法:不加html
return redirect('/cmdb/index/')
3、
根据id删除用户的瞬间跳转到当前页面
<a href="/cmdb/userdel-{{ row.id }}/"> 删除 </a>
def user_del(request,nid):
models.UserInfo.objects.filter(id=nid).delete()
return redirect('/cmdb/user_info/')
4、
注意不成功的话 重新打开一个页面试试
5、
注意:<input type="text" name="id" value="1"/> value的意思是可以在输入框中显示出来id
style="display: none"
6、
注意form表单里面action路径 一定要和 url里面的保持一致,否则报错,
例如:
href="/cmdb/userdetail-{{ row.id }}
url(r'^userdetail-(?P<nid>\d+)/', views.user_detail,),
app01/urls.py
"""第19章 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/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
from app01 import views
from django.conf.urls import url
urlpatterns = [
path('login/', views.login),
path('index/', views.index,),
path('user_info/', views.user_info,),
url(r'^userdetail-(?P<nid>\d+)/', views.user_detail,),
url(r'^userdel-(?P<nid>\d+)/', views.user_del,),
url(r'^useredit-(?P<nid>\d+)/', views.user_edit,),
path('orm/', views.orm),
]
app01/views.py
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.shortcuts import redirect
from app01 import models
import urllib
# Create your views here.
# USER_DICT={
# 'k1':'root1',
# 'k2':'root2',
# 'k3':'root3',
# 'k4':'root4',
# }
USER_DICT={
'1':{'name':'root1','email':'root@123.com'},
'2':{'name':'root2','email':'root@123.com'},
'3':{'name':'root3','email':'root@123.com'},
'4':{'name':'root4','email':'root@123.com'}
}
def index(request):
return render(request,'index.html')
def user_info(request):
if request.method=="GET":
user_list=models.UserInfo.objects.all()
return render(request,'user_info.html',{'user_list':user_list})
elif request.method=="POST":
u=request.POST.get('user')
p=request.POST.get('pwd')
models.UserInfo.objects.create(username=u,password=p)
user_list=models.UserInfo.objects.all()
#print(user_list.query)
return render(request,'user_info.html',{'user_list':user_list})
def user_del(request,nid):
models.UserInfo.objects.filter(id=nid).delete()
return redirect('/cmdb/user_info/')
def user_edit(request,nid):
if request.method=='GET':
obj=models.UserInfo.objects.filter(id=nid).first()
return render(request,'user_edit.html',{'obj':obj})
elif request.method=='POST':
nid=request.POST.get('id')
u=request.POST.get('username')
p=request.POST.get('password')
models.UserInfo.objects.filter(id=nid).update(username=u,password=p)
return redirect('/cmdb/user_detail/')
def user_detail(request,nid):
obj=models.UserInfo.objects.filter(id=nid).first()
return render(request,'user_detail.html',{'obj':obj})
def login(request):
#models.UserGroup.objects.create(caption='DBA')
if request.method=="GET":
return render(request,'login.html')
elif request.method=="POST":
#数据库中执行 select 判断用户名和密码是否中确
u=request.POST.get('user')
p=request.POST.get('pwd')
#count=models.UserInfo.objects.filter(username=u,password=p).count() 也可以,但是不经常用
obj=models.UserInfo.objects.filter(username=u,password=p).first()
#print(obj)
#下面意思:如果obj为真
if obj:
return redirect('/cmdb/index/')
else:
return render(request,'login.html')
else:
return redirect('/index/')
def orm(request):
#创建
#models.UserInfo.objects.create(username='root',password='123',)
# obj=models.UserInfo(username='bob',password='456')
# obj.save()
# dic={'username':'jack','password':'789'}
# models.UserInfo.objects.create(dic)
#查
result=models.UserInfo.objects.all()
#result=models.UserInfo.objects.filter(username='root',password=999)
#
#删除:
#models.UserInfo.objects.filter().delete()
#更新
#models.UserInfo.objects.all().update(password=888)
# obj=models.UserInfo.objects.filter(id=3)
# for i in obj:
# print(i.username)
#
return HttpResponse('orm')
# from django.views import View
#
# class Home(View):
# def dispatch(self, request, *args, **kwargs):
# print('before')#kkkk
# result=super(Home,self).dispatch(request, *args, **kwargs)
# print('after')
# return result
#
# def get(self,request):
# print(request.method)
# return render(request,'home.html')
# def post(self,request):
# print(request.method)
# return render(request,'home.html')
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
margin: 0;
}
.menu{
display: block;
padding: 5px;
}
</style>
</head>
<body>
<div style="height: 48px;background-color: black;color: white">
欢迎到来
</div>
<div>
<div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine">
<a class="menu" href="/cmdb/user_info/">用户管理</a>
<a class="menu" href="/cmdb/user_group/">用户组管理</a>
</div>
</div>
<div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 0;overflow: auto">
</div>
</body>
</html>
templates/login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body >
<form action="/cmdb/login/" method="POST" enctype="multipart/form-data">
<p>
<input type="text" name="user" placeholder="用户名">
</p>
<p>
<input type="password" name="pwd" placeholder="密码">
</p>
<input type="submit" value="提交">
</form>
</body>
</html>
templates/user_info.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body {
margin: 0;
}
.menu {
display: block;
padding: 5px;
}
</style>
</head>
<body>
<div style="height: 48px;background-color: black;color: white">
欢迎到来
</div>
<div>
<div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine">
<a class="menu" href="/cmdb/user_info/">用户管理</a>
<a class="menu" href="/cmdb/user_group/">用户组管理</a>
</div>
</div>
<div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 700px;overflow: auto;background-color: antiquewhite">
<h3>添加用户</h3>
<form action="/cmdb/user_info/" method="post">
<input type="text" name="user"/>
<input type="text" name="pwd"/>
<input type="submit" value="添加"/>
</form>
<h3>用户列表</h3>
<ul>
{% for row in user_list %}
<li><a href="/cmdb/userdetail-{{ row.id }}/">{{ row.username }} </a> |
<a href="/cmdb/userdel-{{ row.id }}/"> 删除 </a> |
<a href="/cmdb/useredit-{{ row.id }}/"> 编辑 </a>
</li>
{% endfor %}
</ul>
</div>
</body>
</html>
templates/user_detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
margin: 0;
}
.menu{
display: block;
padding: 5px;
}
</style>
</head>
<body>
<div style="height: 48px;background-color: black;color: white">
欢迎到来
</div>
<div>
<div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine">
<a class="menu" href="/cmdb/user_info/">用户管理</a>
<a class="menu" href="/cmdb/user_group/">用户组管理</a>
</div>
</div>
<div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 700px;overflow: auto;background-color: antiquewhite">
<h1>用户详细信息</h1>
<h2>{{ obj.id }}</h2>
<h2>{{ obj.name }}</h2>
<h2>{{ obj.password }}</h2>
</div>
</body>
</html>
templates/user_edit.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>编辑用户</h1>
<form method="post" action="/cmdb/useredit-{{ obj.id }}/">
<input style="display: none" type="text" name="id" value="{{ obj.id }}" />
<input type="text" name="username" value="{{ obj.username }}" />
<input type="text" name="password" value="{{ obj.password }}" />
<input type="submit" name="提交" >
</form>
</body>
</html>
19周 16章 Django 字段类型介绍
字符串、数字、时间、二进制、自增
# Create your models here.
class UserGroup(models.Model):
uid=models.AutoField(primary_key=True)
caption=models.CharField(max_length=50)
class UserInfo(models.Model):
#自动创建 id列 自增主键
username=models.CharField(max_length=32)
password=models.CharField(max_length=60)
email=models.CharField(max_length=60)
#gender=models.CharField(max_length=60,null=True)
test=models.EmailField(max_length=20,null=True)
更新表:
password=models.CharField(max_length=60)
make manage.py makemigrations
make manage.py migrate
增加表:
1、
email=models.CharField(max_length=60)
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option: 1
Please enter the default value now, as valid Python
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
Invalid input: name 'jack' is not defined
>>> 'bob'
make manage.py makemigrations
make manage.py migrate
然后关掉软件,重新打开才生效。
2、、
gender=models.CharField(max_length=60,null=True)
make manage.py makemigrations
make manage.py migrate
删除表:
#gender=models.CharField(max_length=60,null=True)
make manage.py makemigrations
make manage.py migrate
自增:
class UserGroup(models.Model):
uid=models.AutoField(primary_key=True)
caption=models.CharField(max_length=50)
19周 17章:Django ORM字段参数介绍: 这些都是在Django admin里面使用
null 数据库中字段是否可以为空
db_column 数据库中字段的列名
db_tablespace
default 数据库中字段的默认值
primary_key 数据库中字段是否为主键
db_index 数据库中字段是否可以建立索引
unique 数据库中字段是否可以建立唯一索引
unique_for_date 数据库中字段【日期】部分是否可以建立唯一索引
unique_for_month 数据库中字段【月】部分是否可以建立唯一索引
unique_for_year 数据库中字段【年】部分是否可以建立唯一索引
verbose_name Admin中显示的字段名称
blank Admin中是否允许用户输入为空
username=models.CharField(max_length=50,blank=True,verbose_name='用户名')
editable Admin中是否可以编辑
help_text Admin中该字段的提示信息
choices Admin中显示选择框的内容,用不变动的数据放在内存中从而避免跨表操作
如:gf = models.IntegerField(choices=[(0, '何穗'),(1, '大表姐'),],default=1)
error_messages 自定义错误信息(字典类型),从而定制想要显示的错误信息;
字典健:null, blank, invalid, invalid_choice, unique, and unique_for_date
如:{'null': "不能为空.", 'invalid': '格式错误'}
validators 自定义错误验证(列表类型),从而定制想要的验证规则
auto_now
uptime=models.DateTimeField(auto_now=True,null=True)
自动更新时间:
错误方式;
obj=UserGroup.objects.filter(id=1).update(caption='CEO')
正确方式;
obj=UserGroup.objects.filter(id=1).first()
obj.caption="CEO"
obj.save()
choices :用在admin
user_type_id=models.IntegerField(choices=user_type_choice,default=1)
user_type_choice=(
(1,'超级用户'),
(2,'白金客户'),
(3,'普通客户'),
)
user_type_id=models.IntegerField(choices=user_type_choice,default=1)
19周 18章:Django ORM外键操作
外键的意思:
主要作用就是把两个数据库表连接起来,比如把员工组表、员工信息表给连接起来
注意python3.7外键的变化:
user_group=models.ForeignKey("UserGroup",to_field='uid',default=1,on_delete=models.CASCADE)
注意:怎么取里面的值
row.user_group 是个对象
user_list=Userinfo.object.all()
for row in user_list:
print(row.user_group_id) = print(row.user_group.uid)
print(row.user_group.caption)
<ul>
{% for row in user_list %}
<li><a href="/cmdb/userdetail-{{ row.id }}/">{{ row.username }}</a>
<span>{{ row.user_group.caption }}</span>
</li>
{% endfor %}
</ul>
实例:接之前的,变动的如下:
app01/models.py
from django.db import models
# Create your models here.
class UserGroup(models.Model):
uid=models.AutoField(primary_key=True)
caption=models.CharField(max_length=50)
ctime=models.DateTimeField(auto_now_add=True,null=True)
uptime=models.DateTimeField(auto_now=True,null=True)
#username=models.CharField(max_length=50,blank=True)
class UserInfo(models.Model):
#自动创建 id列 自增主键
username=models.CharField(max_length=32)
password=models.CharField(max_length=60)
email=models.CharField(max_length=60)
#gender=models.CharField(max_length=60,null=True)
test=models.EmailField(max_length=20,null=True)
username=models.CharField(max_length=50,blank=True,verbose_name='用户名')
user_group=models.ForeignKey("UserGroup",to_field='uid',default=1,on_delete=models.CASCADE)
user_type_choice=(
(1,'超级用户'),
(2,'白金客户'),
(3,'普通客户'),
)
user_type_id=models.IntegerField(choices=user_type_choice,default=1)
templates/user_info.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body {
margin: 0;
}
.menu {
display: block;
padding: 5px;
}
</style>
</head>
<body>
<div style="height: 48px;background-color: black;color: white">
欢迎到来
</div>
<div>
<div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine">
<a class="menu" href="/cmdb/user_info/">用户管理</a>
<a class="menu" href="/cmdb/user_group/">用户组管理</a>
</div>
</div>
<div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 700px;overflow: auto;background-color: antiquewhite">
<h3>添加用户</h3>
<form action="/cmdb/user_info/" method="post">
<input type="text" name="user"/>
<input type="text" name="pwd"/>
<input type="submit" value="添加"/>
</form>
<h3>用户列表</h3>
<ul>
{% for row in user_list %}
<li><a href="/cmdb/userdetail-{{ row.id }}/">{{ row.username }} </a> |
<span>{{ row.user_group.caption }}</span>
<a href="/cmdb/userdel-{{ row.id }}/"> 删除 </a> |
<a href="/cmdb/useredit-{{ row.id }}/"> 编辑 </a>
</li>
{% endfor %}
</ul>
</div>
</body>
</html>
第19章/urls.py
"""第19章 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/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
from app01 import views
from django.conf.urls import url
from django.conf.urls import url,include
import urllib
urlpatterns = [
path('login/', views.login),
path('index/', views.index,),
path('user_info/', views.user_info,),
url(r'^userdetail-(?P<nid>\d+)/', views.user_detail,),
url(r'^userdel-(?P<nid>\d+)/', views.user_del,),
url(r'^useredit-(?P<nid>\d+)/', views.user_edit,),
path('orm/', views.orm),
]
19周 19章: 外键实现增加用户(含select标签)
注意下面多个是这么写:弄得好苦
return render(request,'user_info.html',{'user_list':user_list,"group_list":group_list})
app01/views.py
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.shortcuts import redirect
from app01 import models
import urllib
# Create your views here.
# USER_DICT={
# 'k1':'root1',
# 'k2':'root2',
# 'k3':'root3',
# 'k4':'root4',
# }
USER_DICT={
'1':{'name':'root1','email':'root@123.com'},
'2':{'name':'root2','email':'root@123.com'},
'3':{'name':'root3','email':'root@123.com'},
'4':{'name':'root4','email':'root@123.com'}
}
def index(request):
return render(request,'index.html')
def user_info(request):
if request.method=="GET":
user_list=models.UserInfo.objects.all()
group_list=models.UserGroup.objects.all()
return render(request,'user_info.html',{'user_list':user_list,"group_list":group_list})
elif request.method=="POST":
u=request.POST.get('user')
p=request.POST.get('pwd')
models.UserInfo.objects.create(username=u,password=p)
user_list=models.UserInfo.objects.all()
#print(user_list.query)
return render(request,'user_info.html',{'user_list':user_list})
def user_del(request,nid):
models.UserInfo.objects.filter(id=nid).delete()
return redirect('/cmdb/user_info/')
def user_edit(request,nid):
if request.method=='GET':
obj=models.UserInfo.objects.filter(id=nid).first()
return render(request,'user_edit.html',{'obj':obj})
elif request.method=='POST':
nid=request.POST.get('id')
u=request.POST.get('username')
p=request.POST.get('password')
models.UserInfo.objects.filter(id=nid).update(username=u,password=p)
return redirect('/cmdb/user_detail/')
def user_detail(request,nid):
obj=models.UserInfo.objects.filter(id=nid).first()
return render(request,'user_detail.html',{'obj':obj})
def login(request):
#models.UserGroup.objects.create(caption='DBA')
if request.method=="GET":
return render(request,'login.html')
elif request.method=="POST":
#数据库中执行 select 判断用户名和密码是否中确
u=request.POST.get('user')
p=request.POST.get('pwd')
#count=models.UserInfo.objects.filter(username=u,password=p).count() 也可以,但是不经常用
obj=models.UserInfo.objects.filter(username=u,password=p).first()
#print(obj)
#下面意思:如果obj为真
if obj:
return redirect('/cmdb/index/')
else:
return render(request,'login.html')
else:
return redirect('/index/')
def orm(request):
#创建
#models.UserInfo.objects.create(username='root',password='123',)
# obj=models.UserInfo(username='bob',password='456')
# obj.save()
# dic={'username':'jack','password':'789'}
# models.UserInfo.objects.create(dic)
#查
result=models.UserInfo.objects.all()
#result=models.UserInfo.objects.filter(username='root',password=999)
models.UserInfo.objects.create(
username='root1',
password=123,
email='123@.com',
test='ceshi',
user_group_id=1,
)
#删除:
#models.UserInfo.objects.filter().delete()
#更新
#models.UserInfo.objects.all().update(password=888)
# obj=models.UserInfo.objects.filter(id=3)
# for i in obj:
# print(i.username)
#
return HttpResponse('orm')
# from django.views import View
#
# class Home(View):
# def dispatch(self, request, *args, **kwargs):
# print('before')#kkkk
# result=super(Home,self).dispatch(request, *args, **kwargs)
# print('after')
# return result
#
# def get(self,request):
# print(request.method)
# return render(request,'home.html')
# def post(self,request):
# print(request.method)
# return render(request,'home.html')
app01/models.py
from django.db import models
# Create your models here.
class UserGroup(models.Model):
uid=models.AutoField(primary_key=True)
caption=models.CharField(max_length=50)
ctime=models.DateTimeField(auto_now_add=True,null=True)
uptime=models.DateTimeField(auto_now=True,null=True)
#username=models.CharField(max_length=50,blank=True)
class UserInfo(models.Model):
#自动创建 id列 自增主键
username=models.CharField(max_length=32)
password=models.CharField(max_length=60)
email=models.CharField(max_length=60)
#gender=models.CharField(max_length=60,null=True)
test=models.EmailField(max_length=20,null=True)
username=models.CharField(max_length=50,blank=True,verbose_name='用户名')
user_group=models.ForeignKey("UserGroup",to_field='uid',default=1,on_delete=models.CASCADE)
user_type_choice=(
(1,'超级用户'),
(2,'白金客户'),
(3,'普通客户'),
)
user_type_id=models.IntegerField(choices=user_type_choice,default=1)
app01/urls.py
"""第19章 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/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
from app01 import views
from django.conf.urls import url
from django.conf.urls import url,include
import urllib
urlpatterns = [
path('login/', views.login),
path('index/', views.index,),
path('user_info/', views.user_info,),
url(r'^userdetail-(?P<nid>\d+)/', views.user_detail,),
url(r'^userdel-(?P<nid>\d+)/', views.user_del,),
url(r'^useredit-(?P<nid>\d+)/', views.user_edit,),
path('orm/', views.orm),
]
templates/user_info.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body {
margin: 0;
}
.menu {
display: block;
padding: 5px;
}
</style>
</head>
<body>
<div style="height: 48px;background-color: black;color: white">
欢迎到来
</div>
<div>
<div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine">
<a class="menu" href="/cmdb/user_info/">用户管理</a>
<a class="menu" href="/cmdb/user_group/">用户组管理</a>
</div>
</div>
<div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 700px;overflow: auto;background-color: antiquewhite">
<h3>添加用户</h3>
<form action="/cmdb/user_info/" method="post">
<input type="text" name="user"/>
<input type="text" name="pwd"/>
<select name="group_id">
{% for item in group_list %}
<option value="{{ item.uid }}">{{ item.caption }}</option>
{% endfor %}
</select>
<input type="submit" value="添加"/>
</form>
<h3>用户列表</h3>
<ul>
{% for row in user_list %}
<li><a href="/cmdb/userdetail-{{ row.id }}/">{{ row.username }} </a> |
<span>{{ row.user_group.caption }}</span>
<a href="/cmdb/userdel-{{ row.id }}/"> 删除 </a> |
<a href="/cmdb/useredit-{{ row.id }}/"> 编辑 </a>
</li>
{% endfor %}
</ul>
</div>
</body>
</html>
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
margin: 0;
}
.menu{
display: block;
padding: 5px;
}
</style>
</head>
<body>
<div style="height: 48px;background-color: black;color: white">
欢迎到来
</div>
<div>
<div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine">
<a class="menu" href="/cmdb/user_info/">用户管理</a>
<a class="menu" href="/cmdb/user_group/">用户组管理</a>
</div>
</div>
<div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 0;overflow: auto">
</div>
</body>
</html>
templates/login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body >
<form action="/cmdb/login/" method="POST" enctype="multipart/form-data">
<p>
<input type="text" name="user" placeholder="用户名">
</p>
<p>
<input type="password" name="pwd" placeholder="密码">
</p>
<input type="submit" value="提交">
</form>
</body>
</html>
templates/user_detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
margin: 0;
}
.menu{
display: block;
padding: 5px;
}
</style>
</head>
<body>
<div style="height: 48px;background-color: black;color: white">
欢迎到来
</div>
<div>
<div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine">
<a class="menu" href="/cmdb/user_info/">用户管理</a>
<a class="menu" href="/cmdb/user_group/">用户组管理</a>
</div>
</div>
<div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 700px;overflow: auto;background-color: antiquewhite">
<h1>用户详细信息</h1>
<h2>{{ obj.id }}</h2>
<h2>{{ obj.name }}</h2>
<h2>{{ obj.password }}</h2>
</div>
</body>
</html>
templates/user_edit.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>编辑用户</h1>
<form method="post" action="/cmdb/useredit-{{ obj.id }}/">
<input style="display: none" type="text" name="id" value="{{ obj.id }}" />
<input type="text" name="username" value="{{ obj.username }}" />
<input type="text" name="password" value="{{ obj.password }}" />
<input type="submit" name="提交" >
</form>
</body>
</html>
访问:
http://127.0.0.1:8000/cmdb/user_info/
第20章 03节 Django 一对多创建介绍
第20章 04节 Django 创建 一对多表结构
1、先创建一个工程
app01/models.py
from django.db import models
# Create your models here.
class Business(models.Model):
caption=models.CharField(max_length=32)
class Host(models.Model):
nid=models.AutoField(primary_key=True)
hostname=models.CharField(max_length=32,db_index=True)
ip=models.GenericIPAddressField(protocol="both",max_length=32,db_index=True)
port=models.IntegerField()
b=models.ForeignKey(to="Business",to_field='id',on_delete=models.CASCADE)
第20章-05 获取单表数据的三种方式
models.Business.objects.all()
是个对象
models.Business.objects.values('id','caption')
#[{'id':'1','caption':'运维','code':'sa'}] values 是个字典
models.Business.objects.values_list('id','caption')
#[(1,运维),(2,市场)] values_list 是个元组
第20章/settings.py
"""
Django settings for 第20章 project.
Generated by 'django-admin startproject' using Django 2.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/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/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'u#@z=2@*h^sph5$uqwo+gwgml#ivnq&l@b7-9jg8ve@pmv4z_6'
# 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',
]
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 = '第20章.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 = '第20章.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/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/2.0/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/2.0/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/2.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS=(
os.path.join(BASE_DIR,'static'),
)
app01/models.py
from django.db import models
# Create your models here.
class Business(models.Model):
caption=models.CharField(max_length=32)
code=models.CharField(max_length=32,null=True)
class Host(models.Model):
nid=models.AutoField(primary_key=True)
hostname=models.CharField(max_length=32,db_index=True)
ip=models.GenericIPAddressField(protocol="both",max_length=32,db_index=True)
port=models.IntegerField()
b=models.ForeignKey(to="Business",to_field='id',on_delete=models.CASCADE)
第20章/urls.py
"""第20章 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/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
from app01 import views
from django.conf.urls import url
urlpatterns = [
path('admin/', admin.site.urls),
#path('business/', views.business,),
url(r'^business/$', views.business,),
]
app01/views.py
from django.shortcuts import render
# Create your views here.
from app01 import models
def business(request):
v1=models.Business.objects.all()
v2=models.Business.objects.values('id','caption')
#[{'id':'1','caption':'运维','code':'sa'}] values 对象是个字典
v3=models.Business.objects.values_list('id','caption')
#[(1,运维),(2,市场)] values_list 对象是个元组
return render(request,'business.html',{'v1':v1,'v2':v2,'v3':v3})
templates/business.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>业务线列表(对象)</h1>
<ul>
{% for row in v1 %}
<li>{{ row.id }} - {{ row.caption }} - {{ row.code }}</li>
{% endfor %}
</ul>
<h1>业务线列表(字典)</h1>
<ul>
{% for row in v2 %}
<li>{{ row.id }} - {{ row.caption }} </li>
{% endfor %}
</ul>
<h1>业务线列表(元组)</h1>
<ul>
{% for row in v3 %}
<li>{{ row.0 }} - {{ row.1 }} </li>
{% endfor %}
</ul>
</body>
</html>
第20章-06 一对多跨表操作
实例接上面:
第20章/settings.py
"""
Django settings for 第20章 project.
Generated by 'django-admin startproject' using Django 2.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/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/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'u#@z=2@*h^sph5$uqwo+gwgml#ivnq&l@b7-9jg8ve@pmv4z_6'
# 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',
]
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 = '第20章.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 = '第20章.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/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/2.0/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/2.0/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/2.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS=(
os.path.join(BASE_DIR,'static'),
)
app01/models.py
from django.db import models
# Create your models here.
class Business(models.Model):
caption=models.CharField(max_length=32)
code=models.CharField(max_length=32,null=True)
class Host(models.Model):
nid=models.AutoField(primary_key=True)
hostname=models.CharField(max_length=32,db_index=True)
ip=models.GenericIPAddressField(protocol="both",max_length=32,db_index=True)
port=models.IntegerField()
b=models.ForeignKey(to="Business",to_field='id',on_delete=models.CASCADE)
第20章/urls.py
"""第20章 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/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
from app01 import views
from django.conf.urls import url
urlpatterns = [
path('admin/', admin.site.urls),
#path('business/', views.business,),
url(r'^business/$', views.business,),
url(r'^host/$', views.host,),
]
app01/views.py
from django.shortcuts import render,HttpResponse
# Create your views here.
from app01 import models
def business(request):
v1=models.Business.objects.all()
v2=models.Business.objects.values('id','caption')
#[{'id':'1','caption':'运维','code':'sa'}] values 是个字典
v3=models.Business.objects.values_list('id','caption')
#[(1,运维),(2,市场)] values_list 是个元组
return render(request,'business.html',{'v1':v1,'v2':v2,'v3':v3})
def host(request):
v1=models.Host.objects.filter(nid__gt=0)
return render(request,'host.html',{'v1':v1})
templates/business.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>业务线列表(对象)</h1>
<ul>
{% for row in v1 %}
<li>{{ row.id }} - {{ row.caption }} - {{ row.code }}</li>
{% endfor %}
</ul>
<h1>业务线列表(字典)</h1>
<ul>
{% for row in v2 %}
<li>{{ row.id }} - {{ row.caption }} </li>
{% endfor %}
</ul>
<h1>业务线列表(元组)</h1>
<ul>
{% for row in v3 %}
<li>{{ row.0 }} - {{ row.1 }} </li>
{% endfor %}
</ul>
</body>
</html>
templates/host.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>业务线列表</h1>
<table border="1">
<thead>
<tr>
<th>主机名</th>
<th>ip地址</th>
<th>端口</th>
<th>业务线名称</th>
</tr>
</thead>
<tbody>
{% for row in v1 %}
<tr ht_d="{{ row.nid }}" b_id="{{ row.b.id }}">
<th>{{ row.hostname }}</th>
<th>{{ row.ip }}</th>
<th>{{ row.port }}</th>
<th>{{ row.b.caption }}</th>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
第20周-07 一对多块表操作的三种方式
接上面:
app01/views.py
from django.shortcuts import render,HttpResponse
# Create your views here.
from app01 import models
def business(request):
v1=models.Business.objects.all()
# for row in v1:
# print(row.id,row.caption)
v2=models.Business.objects.values('id','caption')
# for row in v2:
# print(row['id'],row['caption'])
#[{'id':'1','caption':'运维','code':'sa'}] values 是个字典
v3=models.Business.objects.values_list('id','caption')
#[(1,运维),(2,市场)] values_list 是个元组
return render(request,'business.html',{'v1':v1,'v2':v2,'v3':v3})
#return HttpResponse('ok')
def host(request):
v1=models.Host.objects.filter(nid__gt=0)
# for row in v1:
# print(row.nid,row.hostname)
v2=models.Host.objects.filter(nid__gt=0).values('nid','hostname','b_id','b__caption')
# for row in v2:
# print(row['nid'],row['hostname'],row['b_id'])
v3=models.Host.objects.filter(nid__gt=0).values_list('nid','hostname','b_id','b__caption')
# for row in v3:
# print(row[0],row[1])
#return HttpResponse('ok')
return render(request,'host.html',{'v1':v1,'v2':v2,'v3':v3})
templates/host.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>主机列表(列表)</h1>
<table border="1">
<thead>
<tr>
<th>主机名</th>
<th>ip地址</th>
<th>端口</th>
<th>业务线名称</th>
</tr>
</thead>
<tbody>
{% for row in v1 %}
<tr ht-d="{{ row.nid }}" b-id="{{ row.b.id }}">
<th>{{ row.hostname }}</th>
<th>{{ row.ip }}</th>
<th>{{ row.port }}</th>
<th>{{ row.b.caption }}</th>
</tr>
{% endfor %}
<tbody>
</table>
<h1>主机列表(字典)</h1>
<table border="1">
<thead>
<tr>
<th>主机名</th>
<th>ip地址</th>
<th>端口</th>
<th>业务线名称</th>
</tr>
</thead>
<tbody>
{% for row in v1 %}
<tr ht-d="{{ row.nid }}" b-id="{{ row.b.id }}">
<th>{{ row.hostname }}</th>
<th>{{ row.ip }}</th>
<th>{{ row.port }}</th>
<th>{{ row.b.caption }}</th>
</tr>
{% endfor %}
<tbody>
</table>
<h1>业务线列表*(元组)</h1>
<table border="1">
<thead>
<tr>
<th>主机名</th>
<th>ip地址</th>
</tr>
</thead>
<tbody>
{% for row in v3 %}
<tr ht-d="{{ row.0 }}" b-id="{{ row.2 }}">
<th>{{ row.1 }}</th>
<th>{{ row.3 }}</th>
</tr>
{% endfor %}
<tbody>
</table>
</body>
</html>
第20周-09 增加一对多数据示例; --添加主机--用模态对话框演示:
接上面:
app01/views.py
from django.shortcuts import render,HttpResponse,redirect
# Create your views here.
from app01 import models
def business(request):
v1=models.Business.objects.all()
# for row in v1:
# print(row.id,row.caption)
v2=models.Business.objects.values('id','caption')
# for row in v2:
# print(row['id'],row['caption'])
#[{'id':'1','caption':'运维','code':'sa'}] values 是个字典
v3=models.Business.objects.values_list('id','caption')
#[(1,运维),(2,市场)] values_list 是个元组
return render(request,'business.html',{'v1':v1,'v2':v2,'v3':v3})
#return HttpResponse('ok')
def host(request):
if request.method=='GET':
b_list=models.Business.objects.all()
elif request.method=='POST':
h=request.POST.get('hostname')
i=request.POST.get('ip')
p=request.POST.get('port')
b=request.POST.get('b_id')
models.Host.objects.create(hostname=h,ip=i,port=p,b_id=b)
return redirect('/host/')
v1=models.Host.objects.filter(nid__gt=0)
# for row in v1:
# print(row.nid,row.hostname)
v2=models.Host.objects.filter(nid__gt=0).values('nid','hostname','b_id','b__caption')
# for row in v2:
# print(row['nid'],row['hostname'],row['b_id'])
v3=models.Host.objects.filter(nid__gt=0).values_list('nid','hostname','b_id','b__caption')
# for row in v3:
# print(row[0],row[1])
#return HttpResponse('ok')
return render(request,'host.html',{'v1':v1,'v2':v2,'v3':v3,'b_list':b_list})
templates/host.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.hide {
display: none;
}
.shade {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: black;
opacity: 0.6;
z-index: 100;
}
.add-modal {
position: fixed;
height: 300px;
width: 400px;
top: 100px;
left: 50%;
z-index: 101;
border: 1px solid red;
background: white;
margin-left: -200px;
}
</style>
</head>
<body>
<h1>主机列表(列表)</h1>
<div>
<input id="add_host" type="button" value="添加">
</div>
<table border="1">
<thead>
<tr>
<th>序号</th>
<th>主机名</th>
<th>ip地址</th>
<th>端口</th>
<th>业务线名称</th>
</tr>
</thead>
<tbody>
{% for row in v1 %}
<tr ht-d="{{ row.nid }}" b-id="{{ row.b.id }}">
<th>{{ forloop.counter }}</th>
<th>{{ row.hostname }}</th>
<th>{{ row.ip }}</th>
<th>{{ row.port }}</th>
<th>{{ row.b.caption }}</th>
</tr>
{% endfor %}
<tbody>
</table>
<h1>主机列表(字典)</h1>
<table border="1">
<thead>
<tr>
<th>主机名</th>
<th>ip地址</th>
<th>端口</th>
<th>业务线名称</th>
</tr>
</thead>
<tbody>
{% for row in v1 %}
<tr ht-d="{{ row.nid }}" b-id="{{ row.b.id }}">
<th>{{ row.hostname }}</th>
<th>{{ row.ip }}</th>
<th>{{ row.port }}</th>
<th>{{ row.b.caption }}</th>
</tr>
{% endfor %}
<tbody>
</table>
<h1>主机列表*(元组)</h1>
<table border="1">
<thead>
<tr>
<th>主机名</th>
<th>ip地址</th>
</tr>
</thead>
<tbody>
{% for row in v3 %}
<tr ht-d="{{ row.0 }}" b-id="{{ row.2 }}">
<th>{{ row.1 }}</th>
<th>{{ row.3 }}</th>
</tr>
{% endfor %}
<tbody>
</table>
<div class="shade hide"></div>
<div class="add-modal hide">
<form method="post" action="/host/">
<div class="group">
<input type="text" placeholder="主机名" name="hostname">
</div>
<div class="group">
<input type="text" placeholder="IP" name="ip">
</div>
<div class="group">
<input type="text" placeholder="端口" name="port">
</div>
<div class="group">
<select name="b_id">
{% for op in b_list %}
<option value="{{ op.id }}">{{ op.caption }}</option>
{% endfor %}
</select >
<input type="submit" value="提交">
<input id="cancle" type="button" value="取消">
</div>
</form>
</div>
<script src="/static/jquery-3.2.1.js"></script>
<script>
$(function () {
$('#add_host').click(function () {
$('.add-modal,.shade').removeClass('hide');
});
$('#cancle').click(function(){
$('.add-modal,.shade').addClass('hide');
})
})
</script>
</body>
</html>
19周 11章 django ORM基本创建类型以及生成数据库结构
类型:
dbfirst :通过数据库创建类
codefirst:先创建类 再创建数据库 --最常用
ORM的意思: 通过类创建数据库
创建类
1、根据类自动创建书记库表
配置 app下的model.py
2、根据类对数据库表中的数据进行各种操作
class UserInfo(models.Model):
#自动创建 id列 自增主键
username=models.CharField(max_length=32)
password=models.CharField(max_length=64)
执行命令:
python manage.py makemigrations
python manage.py migrate
默认链接 sqlite 如果要链接myaql 需要进行配置:
前提:需要创建mysql表
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME':'dbname',
'USER': 'root',
'PASSWORD': 'xxx',
'HOST': '',
'PORT': '',
}
}
models.py
from django.db import models
# Create your models here.
class UserInfo(models.Model):
#自动创建 id列 自增主键
username=models.CharField(max_length=32)
password=models.CharField(max_length=64)
19周 12章 django ORM使用mysql 注意:
需要先修改pymysql:在project同名文件夹的__init__文件中添加如下代码:
import pymysql
pymysql.install_as_MySql()
19周 13章 django ORM 基本操作 增、删、改、查
1、先导入模块
from app01 import models
创建
models.UserInfo.objects.create(username='root',password='123',)
obj=models.UserInfo(username='bob',password='456')
obj.save()
dic={'username':'jack','password':'789'}
models.UserInfo.objects.create(dic)
查
result=models.UserInfo.objects.all()
result=models.UserInfo.objects.filter(username='root',password=999)
拿到的是一个对象,而且是名字、密码都一样的第一个
obj=models.UserInfo.objects.filter(username=u,password=p).first()
取对象中的某一个数据
obj=models.UserInfo.objects.filter(id=3).first()
print(obj.username)
拿到的是一个列表,而且是名字、密码都一样的多个
obj=models.UserInfo.objects.filter(username=u,password=p)
循环拿列表中的某一个数据:
def orm(request):
obj=models.UserInfo.objects.filter(id=3)
for i in obj:
print(i.username)
return HttpResponse('orm')
删除:
models.UserInfo.objects.filter().delete()
更新
models.UserInfo.objects.all().update(password=888)
models.UserInfo.objects.filter(id=1).update(password=999
第19章\urls.py
urlpatterns = [
url(r'^cmdb/',include("app01.urls")),
url(r'^monitor/',include("app02.urls")),
]
app01\views.py
from app01 import models
def orm(request):
创建
models.UserInfo.objects.create(username='root',password='123',)
obj=models.UserInfo(username='bob',password='456')
obj.save()
dic={'username':'jack','password':'789'}
models.UserInfo.objects.create(dic)
查
result=models.UserInfo.objects.all()
result=models.UserInfo.objects.filter(username='root',password=999)
删除:
models.UserInfo.objects.filter().delete()
更新
models.UserInfo.objects.all().update(password=888)
models.UserInfo.objects.filter(id=1).update(password=999
第19章 14节 基于ORM实现用户登录:
报错问题:
1、访问页面没有内容,返回200错误,说明肯定是html里面的内容写错了
2、ValueError: not enough values to unpack (expected 2, got 1)
这个错误说明:obj=models.UserInfo.objects.filter(id=nid).first() 这个里面没有写“id=”
或者:{'obj':obj} 这个写错了
总之是括号里面的少个东西
3、url一定要写成这样格式,否则很容易报错
url(r'^userdetail-(?P<nid>\d+)/', views.user_detail,),
过程:
app01/urls.py
"""第19章 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/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
from app01 import views
from django.conf.urls import url
urlpatterns = [
path('login/', views.login),
path('index/', views.index,),
path('user_info/', views.user_info,),
url(r'^userdetail-(?P<nid>\d+)/', views.user_detail,),
path('orm/', views.orm),
]
app01/views.py
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.shortcuts import redirect
import urllib
# Create your views here.
# USER_DICT={
# 'k1':'root1',
# 'k2':'root2',
# 'k3':'root3',
# 'k4':'root4',
# }
USER_DICT={
'1':{'name':'root1','email':'root@123.com'},
'2':{'name':'root2','email':'root@123.com'},
'3':{'name':'root3','email':'root@123.com'},
'4':{'name':'root4','email':'root@123.com'}
}
def index(request):
return render(request,'index.html')
def user_info(request):
user_list=models.UserInfo.objects.all()
#print(user_list.query)
return render(request,'user_info.html',{'user_list':user_list})
def user_detail(request,nid):
obj=models.UserInfo.objects.filter(id=nid).first()
return render(request,'user_detail.html',{'obj':obj})
def login(request):
if request.method=="GET":
return render(request,'login.html')
elif request.method=="POST":
#数据库中执行 select 判断用户名和密码是否中确
u=request.POST.get('user')
p=request.POST.get('pwd')
#count=models.UserInfo.objects.filter(username=u,password=p).count() 也可以,但是不经常用
obj=models.UserInfo.objects.filter(username=u, password=p).first()
#print(obj)
#下面意思:如果obj为真
if obj:
return redirect('/cmdb/index/')
else:
return render(request,'login.html')
else:
return redirect('/index/')
from app01 import models
def orm(request):
#创建
#models.UserInfo.objects.create(username='root',password='123',)
# obj=models.UserInfo(username='bob',password='456')
# obj.save()
# dic={'username':'jack','password':'789'}
# models.UserInfo.objects.create(dic)
#查
result=models.UserInfo.objects.all()
#result=models.UserInfo.objects.filter(username='root',password=999)
#
#删除:
#models.UserInfo.objects.filter().delete()
#更新
#models.UserInfo.objects.all().update(password=888)
# obj=models.UserInfo.objects.filter(id=3)
# for i in obj:
# print(i.username)
#
return HttpResponse('orm')
# from django.views import View
#
# class Home(View):
# def dispatch(self, request, *args, **kwargs):
# print('before')#kkkk
# result=super(Home,self).dispatch(request, *args, **kwargs)
# print('after')
# return result
#
# def get(self,request):
# print(request.method)
# return render(request,'home.html')
# def post(self,request):
# print(request.method)
# return render(request,'home.html')
templates/login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body >
<form action="/cmdb/login/" method="POST" enctype="multipart/form-data">
<p>
<input type="text" name="user" placeholder="用户名">
</p>
<p>
<input type="password" name="pwd" placeholder="密码">
</p>
<input type="submit" value="提交">
</form>
</body>
</html>
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
margin: 0;
}
.menu{
display: block;
padding: 5px;
}
</style>
</head>
<body>
<div style="height: 48px;background-color: black;color: white">
欢迎到来
</div>
<div>
<div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine">
<a class="menu" href="/cmdb/user_info/">用户管理</a>
<a class="menu" href="/cmdb/user_group/">用户组管理</a>
</div>
</div>
<div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 0;overflow: auto">
</div>
</body>
</html>
templates/user_info.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
margin: 0;
}
.menu{
display: block;
padding: 5px;
}
</style>
</head>
<body>
<div style="height: 48px;background-color: black;color: white">
欢迎到来
</div>
<div>
<div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine">
<a class="menu" href="/cmdb/user_info/">用户管理</a>
<a class="menu" href="/cmdb/user_group/">用户组管理</a>
</div>
</div>
<div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 700px;overflow: auto;background-color: antiquewhite">
<h3>用户列表</h3>
<ul>
{% for row in user_list %}
<li><a href="/cmdb/userdetail-{{ row.id }}/">{{ row.username }}</a></li>
{% endfor %}
</ul>
</div>
</body>
</html>
templates/user_detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
margin: 0;
}
.menu{
display: block;
padding: 5px;
}
</style>
</head>
<body>
<div style="height: 48px;background-color: black;color: white">
欢迎到来
</div>
<div>
<div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine">
<a class="menu" href="/cmdb/user_info/">用户管理</a>
<a class="menu" href="/cmdb/user_group/">用户组管理</a>
</div>
</div>
<div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 700px;overflow: auto;background-color: antiquewhite">
<h1>用户详细信息</h1>
<h2>{{ obj.id }}</h2>
<h2>{{ obj.name }}</h2>
<h2>{{ obj.password }}</h2>
</div>
</body>
</html>
19周-15章python基于 Django 基于ORM实现用户增加、删除、修改、查看
models.Business.objects.all()
是个对象
models.Business.objects.values('id','caption')
#[{'id':'1','caption':'运维','code':'sa'}] values 是个字典
models.Business.objects.values_list('id','caption')
#[(1,运维),(2,市场)] values_list 是个元组
1、
注意:method="post" 一定要写。一定是小写 否则报错
<form action="/cmdb/user_info/" method="post">
2、
注意href和action、return redirect三个的区分,容易混淆
这是做的跳转:
<a class="menu" href="/cmdb/user_info/">用户管理</a>
这是提交的当前的页面:
<form method="post" action="/cmdb/useredit-{{ obj.id }}/">
这个不加html
return redirect用法:不加html
return redirect('/cmdb/index/')
3、
根据id删除用户的瞬间跳转到当前页面
<a href="/cmdb/userdel-{{ row.id }}/"> 删除 </a>
def user_del(request,nid):
models.UserInfo.objects.filter(id=nid).delete()
return redirect('/cmdb/user_info/')
4、
注意不成功的话 重新打开一个页面试试
5、
注意:<input type="text" name="id" value="1"/> value的意思是可以在输入框中显示出来id
style="display: none"
6、
注意form表单里面action路径 一定要和 url里面的保持一致,否则报错,
例如:
href="/cmdb/userdetail-{{ row.id }}
url(r'^userdetail-(?P<nid>\d+)/', views.user_detail,),
app01/urls.py
"""第19章 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/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
from app01 import views
from django.conf.urls import url
urlpatterns = [
path('login/', views.login),
path('index/', views.index,),
path('user_info/', views.user_info,),
url(r'^userdetail-(?P<nid>\d+)/', views.user_detail,),
url(r'^userdel-(?P<nid>\d+)/', views.user_del,),
url(r'^useredit-(?P<nid>\d+)/', views.user_edit,),
path('orm/', views.orm),
]
app01/views.py
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.shortcuts import redirect
from app01 import models
import urllib
# Create your views here.
# USER_DICT={
# 'k1':'root1',
# 'k2':'root2',
# 'k3':'root3',
# 'k4':'root4',
# }
USER_DICT={
'1':{'name':'root1','email':'root@123.com'},
'2':{'name':'root2','email':'root@123.com'},
'3':{'name':'root3','email':'root@123.com'},
'4':{'name':'root4','email':'root@123.com'}
}
def index(request):
return render(request,'index.html')
def user_info(request):
if request.method=="GET":
user_list=models.UserInfo.objects.all()
return render(request,'user_info.html',{'user_list':user_list})
elif request.method=="POST":
u=request.POST.get('user')
p=request.POST.get('pwd')
models.UserInfo.objects.create(username=u,password=p)
user_list=models.UserInfo.objects.all()
#print(user_list.query)
return render(request,'user_info.html',{'user_list':user_list})
def user_del(request,nid):
models.UserInfo.objects.filter(id=nid).delete()
return redirect('/cmdb/user_info/')
def user_edit(request,nid):
if request.method=='GET':
obj=models.UserInfo.objects.filter(id=nid).first()
return render(request,'user_edit.html',{'obj':obj})
elif request.method=='POST':
nid=request.POST.get('id')
u=request.POST.get('username')
p=request.POST.get('password')
models.UserInfo.objects.filter(id=nid).update(username=u,password=p)
return redirect('/cmdb/user_detail/')
def user_detail(request,nid):
obj=models.UserInfo.objects.filter(id=nid).first()
return render(request,'user_detail.html',{'obj':obj})
def login(request):
#models.UserGroup.objects.create(caption='DBA')
if request.method=="GET":
return render(request,'login.html')
elif request.method=="POST":
#数据库中执行 select 判断用户名和密码是否中确
u=request.POST.get('user')
p=request.POST.get('pwd')
#count=models.UserInfo.objects.filter(username=u,password=p).count() 也可以,但是不经常用
obj=models.UserInfo.objects.filter(username=u,password=p).first()
#print(obj)
#下面意思:如果obj为真
if obj:
return redirect('/cmdb/index/')
else:
return render(request,'login.html')
else:
return redirect('/index/')
def orm(request):
#创建
#models.UserInfo.objects.create(username='root',password='123',)
# obj=models.UserInfo(username='bob',password='456')
# obj.save()
# dic={'username':'jack','password':'789'}
# models.UserInfo.objects.create(dic)
#查
result=models.UserInfo.objects.all()
#result=models.UserInfo.objects.filter(username='root',password=999)
#
#删除:
#models.UserInfo.objects.filter().delete()
#更新
#models.UserInfo.objects.all().update(password=888)
# obj=models.UserInfo.objects.filter(id=3)
# for i in obj:
# print(i.username)
#
return HttpResponse('orm')
# from django.views import View
#
# class Home(View):
# def dispatch(self, request, *args, **kwargs):
# print('before')#kkkk
# result=super(Home,self).dispatch(request, *args, **kwargs)
# print('after')
# return result
#
# def get(self,request):
# print(request.method)
# return render(request,'home.html')
# def post(self,request):
# print(request.method)
# return render(request,'home.html')
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
margin: 0;
}
.menu{
display: block;
padding: 5px;
}
</style>
</head>
<body>
<div style="height: 48px;background-color: black;color: white">
欢迎到来
</div>
<div>
<div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine">
<a class="menu" href="/cmdb/user_info/">用户管理</a>
<a class="menu" href="/cmdb/user_group/">用户组管理</a>
</div>
</div>
<div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 0;overflow: auto">
</div>
</body>
</html>
templates/login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body >
<form action="/cmdb/login/" method="POST" enctype="multipart/form-data">
<p>
<input type="text" name="user" placeholder="用户名">
</p>
<p>
<input type="password" name="pwd" placeholder="密码">
</p>
<input type="submit" value="提交">
</form>
</body>
</html>
templates/user_info.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body {
margin: 0;
}
.menu {
display: block;
padding: 5px;
}
</style>
</head>
<body>
<div style="height: 48px;background-color: black;color: white">
欢迎到来
</div>
<div>
<div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine">
<a class="menu" href="/cmdb/user_info/">用户管理</a>
<a class="menu" href="/cmdb/user_group/">用户组管理</a>
</div>
</div>
<div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 700px;overflow: auto;background-color: antiquewhite">
<h3>添加用户</h3>
<form action="/cmdb/user_info/" method="post">
<input type="text" name="user"/>
<input type="text" name="pwd"/>
<input type="submit" value="添加"/>
</form>
<h3>用户列表</h3>
<ul>
{% for row in user_list %}
<li><a href="/cmdb/userdetail-{{ row.id }}/">{{ row.username }} </a> |
<a href="/cmdb/userdel-{{ row.id }}/"> 删除 </a> |
<a href="/cmdb/useredit-{{ row.id }}/"> 编辑 </a>
</li>
{% endfor %}
</ul>
</div>
</body>
</html>
templates/user_detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
margin: 0;
}
.menu{
display: block;
padding: 5px;
}
</style>
</head>
<body>
<div style="height: 48px;background-color: black;color: white">
欢迎到来
</div>
<div>
<div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine">
<a class="menu" href="/cmdb/user_info/">用户管理</a>
<a class="menu" href="/cmdb/user_group/">用户组管理</a>
</div>
</div>
<div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 700px;overflow: auto;background-color: antiquewhite">
<h1>用户详细信息</h1>
<h2>{{ obj.id }}</h2>
<h2>{{ obj.name }}</h2>
<h2>{{ obj.password }}</h2>
</div>
</body>
</html>
templates/user_edit.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>编辑用户</h1>
<form method="post" action="/cmdb/useredit-{{ obj.id }}/">
<input style="display: none" type="text" name="id" value="{{ obj.id }}" />
<input type="text" name="username" value="{{ obj.username }}" />
<input type="text" name="password" value="{{ obj.password }}" />
<input type="submit" name="提交" >
</form>
</body>
</html>
19周 16章 Django 字段类型介绍
字符串、数字、时间、二进制、自增
# Create your models here.
class UserGroup(models.Model):
uid=models.AutoField(primary_key=True)
caption=models.CharField(max_length=50)
class UserInfo(models.Model):
#自动创建 id列 自增主键
username=models.CharField(max_length=32)
password=models.CharField(max_length=60)
email=models.CharField(max_length=60)
#gender=models.CharField(max_length=60,null=True)
test=models.EmailField(max_length=20,null=True)
更新表:
password=models.CharField(max_length=60)
make manage.py makemigrations
make manage.py migrate
增加表:
1、
email=models.CharField(max_length=60)
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option: 1
Please enter the default value now, as valid Python
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
Invalid input: name 'jack' is not defined
>>> 'bob'
make manage.py makemigrations
make manage.py migrate
然后关掉软件,重新打开才生效。
2、、
gender=models.CharField(max_length=60,null=True)
make manage.py makemigrations
make manage.py migrate
删除表:
#gender=models.CharField(max_length=60,null=True)
make manage.py makemigrations
make manage.py migrate
自增:
class UserGroup(models.Model):
uid=models.AutoField(primary_key=True)
caption=models.CharField(max_length=50)
19周 17章:Django ORM字段参数介绍: 这些都是在Django admin里面使用
null 数据库中字段是否可以为空
db_column 数据库中字段的列名
db_tablespace
default 数据库中字段的默认值
primary_key 数据库中字段是否为主键
db_index 数据库中字段是否可以建立索引
unique 数据库中字段是否可以建立唯一索引
unique_for_date 数据库中字段【日期】部分是否可以建立唯一索引
unique_for_month 数据库中字段【月】部分是否可以建立唯一索引
unique_for_year 数据库中字段【年】部分是否可以建立唯一索引
verbose_name Admin中显示的字段名称
blank Admin中是否允许用户输入为空
username=models.CharField(max_length=50,blank=True,verbose_name='用户名')
editable Admin中是否可以编辑
help_text Admin中该字段的提示信息
choices Admin中显示选择框的内容,用不变动的数据放在内存中从而避免跨表操作
如:gf = models.IntegerField(choices=[(0, '何穗'),(1, '大表姐'),],default=1)
error_messages 自定义错误信息(字典类型),从而定制想要显示的错误信息;
字典健:null, blank, invalid, invalid_choice, unique, and unique_for_date
如:{'null': "不能为空.", 'invalid': '格式错误'}
validators 自定义错误验证(列表类型),从而定制想要的验证规则
auto_now
uptime=models.DateTimeField(auto_now=True,null=True)
自动更新时间:
错误方式;
obj=UserGroup.objects.filter(id=1).update(caption='CEO')
正确方式;
obj=UserGroup.objects.filter(id=1).first()
obj.caption="CEO"
obj.save()
choices :用在admin
user_type_id=models.IntegerField(choices=user_type_choice,default=1)
user_type_choice=(
(1,'超级用户'),
(2,'白金客户'),
(3,'普通客户'),
)
user_type_id=models.IntegerField(choices=user_type_choice,default=1)
19周 18章:Django ORM外键操作
外键的意思:
主要作用就是把两个数据库表连接起来,比如把员工组表、员工信息表给连接起来
注意python3.7外键的变化:
user_group=models.ForeignKey("UserGroup",to_field='uid',default=1,on_delete=models.CASCADE)
注意:怎么取里面的值
row.user_group 是个对象
user_list=Userinfo.object.all()
for row in user_list:
print(row.user_group_id) = print(row.user_group.uid)
print(row.user_group.caption)
<ul>
{% for row in user_list %}
<li><a href="/cmdb/userdetail-{{ row.id }}/">{{ row.username }}</a>
<span>{{ row.user_group.caption }}</span>
</li>
{% endfor %}
</ul>
实例:接之前的,变动的如下:
app01/models.py
from django.db import models
# Create your models here.
class UserGroup(models.Model):
uid=models.AutoField(primary_key=True)
caption=models.CharField(max_length=50)
ctime=models.DateTimeField(auto_now_add=True,null=True)
uptime=models.DateTimeField(auto_now=True,null=True)
#username=models.CharField(max_length=50,blank=True)
class UserInfo(models.Model):
#自动创建 id列 自增主键
username=models.CharField(max_length=32)
password=models.CharField(max_length=60)
email=models.CharField(max_length=60)
#gender=models.CharField(max_length=60,null=True)
test=models.EmailField(max_length=20,null=True)
username=models.CharField(max_length=50,blank=True,verbose_name='用户名')
user_group=models.ForeignKey("UserGroup",to_field='uid',default=1,on_delete=models.CASCADE)
user_type_choice=(
(1,'超级用户'),
(2,'白金客户'),
(3,'普通客户'),
)
user_type_id=models.IntegerField(choices=user_type_choice,default=1)
templates/user_info.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body {
margin: 0;
}
.menu {
display: block;
padding: 5px;
}
</style>
</head>
<body>
<div style="height: 48px;background-color: black;color: white">
欢迎到来
</div>
<div>
<div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine">
<a class="menu" href="/cmdb/user_info/">用户管理</a>
<a class="menu" href="/cmdb/user_group/">用户组管理</a>
</div>
</div>
<div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 700px;overflow: auto;background-color: antiquewhite">
<h3>添加用户</h3>
<form action="/cmdb/user_info/" method="post">
<input type="text" name="user"/>
<input type="text" name="pwd"/>
<input type="submit" value="添加"/>
</form>
<h3>用户列表</h3>
<ul>
{% for row in user_list %}
<li><a href="/cmdb/userdetail-{{ row.id }}/">{{ row.username }} </a> |
<span>{{ row.user_group.caption }}</span>
<a href="/cmdb/userdel-{{ row.id }}/"> 删除 </a> |
<a href="/cmdb/useredit-{{ row.id }}/"> 编辑 </a>
</li>
{% endfor %}
</ul>
</div>
</body>
</html>
第19章/urls.py
"""第19章 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/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
from app01 import views
from django.conf.urls import url
from django.conf.urls import url,include
import urllib
urlpatterns = [
path('login/', views.login),
path('index/', views.index,),
path('user_info/', views.user_info,),
url(r'^userdetail-(?P<nid>\d+)/', views.user_detail,),
url(r'^userdel-(?P<nid>\d+)/', views.user_del,),
url(r'^useredit-(?P<nid>\d+)/', views.user_edit,),
path('orm/', views.orm),
]
19周 19章: 外键实现增加用户(含select标签)
注意下面多个是这么写:弄得好苦
return render(request,'user_info.html',{'user_list':user_list,"group_list":group_list})
app01/views.py
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.shortcuts import redirect
from app01 import models
import urllib
# Create your views here.
# USER_DICT={
# 'k1':'root1',
# 'k2':'root2',
# 'k3':'root3',
# 'k4':'root4',
# }
USER_DICT={
'1':{'name':'root1','email':'root@123.com'},
'2':{'name':'root2','email':'root@123.com'},
'3':{'name':'root3','email':'root@123.com'},
'4':{'name':'root4','email':'root@123.com'}
}
def index(request):
return render(request,'index.html')
def user_info(request):
if request.method=="GET":
user_list=models.UserInfo.objects.all()
group_list=models.UserGroup.objects.all()
return render(request,'user_info.html',{'user_list':user_list,"group_list":group_list})
elif request.method=="POST":
u=request.POST.get('user')
p=request.POST.get('pwd')
models.UserInfo.objects.create(username=u,password=p)
user_list=models.UserInfo.objects.all()
#print(user_list.query)
return render(request,'user_info.html',{'user_list':user_list})
def user_del(request,nid):
models.UserInfo.objects.filter(id=nid).delete()
return redirect('/cmdb/user_info/')
def user_edit(request,nid):
if request.method=='GET':
obj=models.UserInfo.objects.filter(id=nid).first()
return render(request,'user_edit.html',{'obj':obj})
elif request.method=='POST':
nid=request.POST.get('id')
u=request.POST.get('username')
p=request.POST.get('password')
models.UserInfo.objects.filter(id=nid).update(username=u,password=p)
return redirect('/cmdb/user_detail/')
def user_detail(request,nid):
obj=models.UserInfo.objects.filter(id=nid).first()
return render(request,'user_detail.html',{'obj':obj})
def login(request):
#models.UserGroup.objects.create(caption='DBA')
if request.method=="GET":
return render(request,'login.html')
elif request.method=="POST":
#数据库中执行 select 判断用户名和密码是否中确
u=request.POST.get('user')
p=request.POST.get('pwd')
#count=models.UserInfo.objects.filter(username=u,password=p).count() 也可以,但是不经常用
obj=models.UserInfo.objects.filter(username=u,password=p).first()
#print(obj)
#下面意思:如果obj为真
if obj:
return redirect('/cmdb/index/')
else:
return render(request,'login.html')
else:
return redirect('/index/')
def orm(request):
#创建
#models.UserInfo.objects.create(username='root',password='123',)
# obj=models.UserInfo(username='bob',password='456')
# obj.save()
# dic={'username':'jack','password':'789'}
# models.UserInfo.objects.create(dic)
#查
result=models.UserInfo.objects.all()
#result=models.UserInfo.objects.filter(username='root',password=999)
models.UserInfo.objects.create(
username='root1',
password=123,
email='123@.com',
test='ceshi',
user_group_id=1,
)
#删除:
#models.UserInfo.objects.filter().delete()
#更新
#models.UserInfo.objects.all().update(password=888)
# obj=models.UserInfo.objects.filter(id=3)
# for i in obj:
# print(i.username)
#
return HttpResponse('orm')
# from django.views import View
#
# class Home(View):
# def dispatch(self, request, *args, **kwargs):
# print('before')#kkkk
# result=super(Home,self).dispatch(request, *args, **kwargs)
# print('after')
# return result
#
# def get(self,request):
# print(request.method)
# return render(request,'home.html')
# def post(self,request):
# print(request.method)
# return render(request,'home.html')
app01/models.py
from django.db import models
# Create your models here.
class UserGroup(models.Model):
uid=models.AutoField(primary_key=True)
caption=models.CharField(max_length=50)
ctime=models.DateTimeField(auto_now_add=True,null=True)
uptime=models.DateTimeField(auto_now=True,null=True)
#username=models.CharField(max_length=50,blank=True)
class UserInfo(models.Model):
#自动创建 id列 自增主键
username=models.CharField(max_length=32)
password=models.CharField(max_length=60)
email=models.CharField(max_length=60)
#gender=models.CharField(max_length=60,null=True)
test=models.EmailField(max_length=20,null=True)
username=models.CharField(max_length=50,blank=True,verbose_name='用户名')
user_group=models.ForeignKey("UserGroup",to_field='uid',default=1,on_delete=models.CASCADE)
user_type_choice=(
(1,'超级用户'),
(2,'白金客户'),
(3,'普通客户'),
)
user_type_id=models.IntegerField(choices=user_type_choice,default=1)
app01/urls.py
"""第19章 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/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
from app01 import views
from django.conf.urls import url
from django.conf.urls import url,include
import urllib
urlpatterns = [
path('login/', views.login),
path('index/', views.index,),
path('user_info/', views.user_info,),
url(r'^userdetail-(?P<nid>\d+)/', views.user_detail,),
url(r'^userdel-(?P<nid>\d+)/', views.user_del,),
url(r'^useredit-(?P<nid>\d+)/', views.user_edit,),
path('orm/', views.orm),
]
templates/user_info.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body {
margin: 0;
}
.menu {
display: block;
padding: 5px;
}
</style>
</head>
<body>
<div style="height: 48px;background-color: black;color: white">
欢迎到来
</div>
<div>
<div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine">
<a class="menu" href="/cmdb/user_info/">用户管理</a>
<a class="menu" href="/cmdb/user_group/">用户组管理</a>
</div>
</div>
<div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 700px;overflow: auto;background-color: antiquewhite">
<h3>添加用户</h3>
<form action="/cmdb/user_info/" method="post">
<input type="text" name="user"/>
<input type="text" name="pwd"/>
<select name="group_id">
{% for item in group_list %}
<option value="{{ item.uid }}">{{ item.caption }}</option>
{% endfor %}
</select>
<input type="submit" value="添加"/>
</form>
<h3>用户列表</h3>
<ul>
{% for row in user_list %}
<li><a href="/cmdb/userdetail-{{ row.id }}/">{{ row.username }} </a> |
<span>{{ row.user_group.caption }}</span>
<a href="/cmdb/userdel-{{ row.id }}/"> 删除 </a> |
<a href="/cmdb/useredit-{{ row.id }}/"> 编辑 </a>
</li>
{% endfor %}
</ul>
</div>
</body>
</html>
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
margin: 0;
}
.menu{
display: block;
padding: 5px;
}
</style>
</head>
<body>
<div style="height: 48px;background-color: black;color: white">
欢迎到来
</div>
<div>
<div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine">
<a class="menu" href="/cmdb/user_info/">用户管理</a>
<a class="menu" href="/cmdb/user_group/">用户组管理</a>
</div>
</div>
<div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 0;overflow: auto">
</div>
</body>
</html>
templates/login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body >
<form action="/cmdb/login/" method="POST" enctype="multipart/form-data">
<p>
<input type="text" name="user" placeholder="用户名">
</p>
<p>
<input type="password" name="pwd" placeholder="密码">
</p>
<input type="submit" value="提交">
</form>
</body>
</html>
templates/user_detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
margin: 0;
}
.menu{
display: block;
padding: 5px;
}
</style>
</head>
<body>
<div style="height: 48px;background-color: black;color: white">
欢迎到来
</div>
<div>
<div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine">
<a class="menu" href="/cmdb/user_info/">用户管理</a>
<a class="menu" href="/cmdb/user_group/">用户组管理</a>
</div>
</div>
<div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 700px;overflow: auto;background-color: antiquewhite">
<h1>用户详细信息</h1>
<h2>{{ obj.id }}</h2>
<h2>{{ obj.name }}</h2>
<h2>{{ obj.password }}</h2>
</div>
</body>
</html>
templates/user_edit.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>编辑用户</h1>
<form method="post" action="/cmdb/useredit-{{ obj.id }}/">
<input style="display: none" type="text" name="id" value="{{ obj.id }}" />
<input type="text" name="username" value="{{ obj.username }}" />
<input type="text" name="password" value="{{ obj.password }}" />
<input type="submit" name="提交" >
</form>
</body>
</html>
访问:
http://127.0.0.1:8000/cmdb/user_info/
第20章 03节 Django 一对多创建介绍
第20章 04节 Django 创建 一对多表结构
1、先创建一个工程
app01/models.py
from django.db import models
# Create your models here.
class Business(models.Model):
caption=models.CharField(max_length=32)
class Host(models.Model):
nid=models.AutoField(primary_key=True)
hostname=models.CharField(max_length=32,db_index=True)
ip=models.GenericIPAddressField(protocol="both",max_length=32,db_index=True)
port=models.IntegerField()
b=models.ForeignKey(to="Business",to_field='id',on_delete=models.CASCADE)
第20章-05 获取单表数据的三种方式
models.Business.objects.all()
是个对象
models.Business.objects.values('id','caption')
#[{'id':'1','caption':'运维','code':'sa'}] values 是个字典
models.Business.objects.values_list('id','caption')
#[(1,运维),(2,市场)] values_list 是个元组
第20章/settings.py
"""
Django settings for 第20章 project.
Generated by 'django-admin startproject' using Django 2.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/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/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'u#@z=2@*h^sph5$uqwo+gwgml#ivnq&l@b7-9jg8ve@pmv4z_6'
# 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',
]
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 = '第20章.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 = '第20章.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/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/2.0/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/2.0/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/2.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS=(
os.path.join(BASE_DIR,'static'),
)
app01/models.py
from django.db import models
# Create your models here.
class Business(models.Model):
caption=models.CharField(max_length=32)
code=models.CharField(max_length=32,null=True)
class Host(models.Model):
nid=models.AutoField(primary_key=True)
hostname=models.CharField(max_length=32,db_index=True)
ip=models.GenericIPAddressField(protocol="both",max_length=32,db_index=True)
port=models.IntegerField()
b=models.ForeignKey(to="Business",to_field='id',on_delete=models.CASCADE)
第20章/urls.py
"""第20章 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/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
from app01 import views
from django.conf.urls import url
urlpatterns = [
path('admin/', admin.site.urls),
#path('business/', views.business,),
url(r'^business/$', views.business,),
]
app01/views.py
from django.shortcuts import render
# Create your views here.
from app01 import models
def business(request):
v1=models.Business.objects.all()
v2=models.Business.objects.values('id','caption')
#[{'id':'1','caption':'运维','code':'sa'}] values 对象是个字典
v3=models.Business.objects.values_list('id','caption')
#[(1,运维),(2,市场)] values_list 对象是个元组
return render(request,'business.html',{'v1':v1,'v2':v2,'v3':v3})
templates/business.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>业务线列表(对象)</h1>
<ul>
{% for row in v1 %}
<li>{{ row.id }} - {{ row.caption }} - {{ row.code }}</li>
{% endfor %}
</ul>
<h1>业务线列表(字典)</h1>
<ul>
{% for row in v2 %}
<li>{{ row.id }} - {{ row.caption }} </li>
{% endfor %}
</ul>
<h1>业务线列表(元组)</h1>
<ul>
{% for row in v3 %}
<li>{{ row.0 }} - {{ row.1 }} </li>
{% endfor %}
</ul>
</body>
</html>
第20章-06 一对多跨表操作
实例接上面:
第20章/settings.py
"""
Django settings for 第20章 project.
Generated by 'django-admin startproject' using Django 2.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/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/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'u#@z=2@*h^sph5$uqwo+gwgml#ivnq&l@b7-9jg8ve@pmv4z_6'
# 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',
]
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 = '第20章.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 = '第20章.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/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/2.0/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/2.0/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/2.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS=(
os.path.join(BASE_DIR,'static'),
)
app01/models.py
from django.db import models
# Create your models here.
class Business(models.Model):
caption=models.CharField(max_length=32)
code=models.CharField(max_length=32,null=True)
class Host(models.Model):
nid=models.AutoField(primary_key=True)
hostname=models.CharField(max_length=32,db_index=True)
ip=models.GenericIPAddressField(protocol="both",max_length=32,db_index=True)
port=models.IntegerField()
b=models.ForeignKey(to="Business",to_field='id',on_delete=models.CASCADE)
第20章/urls.py
"""第20章 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/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
from app01 import views
from django.conf.urls import url
urlpatterns = [
path('admin/', admin.site.urls),
#path('business/', views.business,),
url(r'^business/$', views.business,),
url(r'^host/$', views.host,),
]
app01/views.py
from django.shortcuts import render,HttpResponse
# Create your views here.
from app01 import models
def business(request):
v1=models.Business.objects.all()
v2=models.Business.objects.values('id','caption')
#[{'id':'1','caption':'运维','code':'sa'}] values 是个字典
v3=models.Business.objects.values_list('id','caption')
#[(1,运维),(2,市场)] values_list 是个元组
return render(request,'business.html',{'v1':v1,'v2':v2,'v3':v3})
def host(request):
v1=models.Host.objects.filter(nid__gt=0)
return render(request,'host.html',{'v1':v1})
templates/business.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>业务线列表(对象)</h1>
<ul>
{% for row in v1 %}
<li>{{ row.id }} - {{ row.caption }} - {{ row.code }}</li>
{% endfor %}
</ul>
<h1>业务线列表(字典)</h1>
<ul>
{% for row in v2 %}
<li>{{ row.id }} - {{ row.caption }} </li>
{% endfor %}
</ul>
<h1>业务线列表(元组)</h1>
<ul>
{% for row in v3 %}
<li>{{ row.0 }} - {{ row.1 }} </li>
{% endfor %}
</ul>
</body>
</html>
templates/host.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>业务线列表</h1>
<table border="1">
<thead>
<tr>
<th>主机名</th>
<th>ip地址</th>
<th>端口</th>
<th>业务线名称</th>
</tr>
</thead>
<tbody>
{% for row in v1 %}
<tr ht_d="{{ row.nid }}" b_id="{{ row.b.id }}">
<th>{{ row.hostname }}</th>
<th>{{ row.ip }}</th>
<th>{{ row.port }}</th>
<th>{{ row.b.caption }}</th>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
第20周-07 一对多块表操作的三种方式
接上面:
app01/views.py
from django.shortcuts import render,HttpResponse
# Create your views here.
from app01 import models
def business(request):
v1=models.Business.objects.all()
# for row in v1:
# print(row.id,row.caption)
v2=models.Business.objects.values('id','caption')
# for row in v2:
# print(row['id'],row['caption'])
#[{'id':'1','caption':'运维','code':'sa'}] values 是个字典
v3=models.Business.objects.values_list('id','caption')
#[(1,运维),(2,市场)] values_list 是个元组
return render(request,'business.html',{'v1':v1,'v2':v2,'v3':v3})
#return HttpResponse('ok')
def host(request):
v1=models.Host.objects.filter(nid__gt=0)
# for row in v1:
# print(row.nid,row.hostname)
v2=models.Host.objects.filter(nid__gt=0).values('nid','hostname','b_id','b__caption')
# for row in v2:
# print(row['nid'],row['hostname'],row['b_id'])
v3=models.Host.objects.filter(nid__gt=0).values_list('nid','hostname','b_id','b__caption')
# for row in v3:
# print(row[0],row[1])
#return HttpResponse('ok')
return render(request,'host.html',{'v1':v1,'v2':v2,'v3':v3})
templates/host.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>主机列表(列表)</h1>
<table border="1">
<thead>
<tr>
<th>主机名</th>
<th>ip地址</th>
<th>端口</th>
<th>业务线名称</th>
</tr>
</thead>
<tbody>
{% for row in v1 %}
<tr ht-d="{{ row.nid }}" b-id="{{ row.b.id }}">
<th>{{ row.hostname }}</th>
<th>{{ row.ip }}</th>
<th>{{ row.port }}</th>
<th>{{ row.b.caption }}</th>
</tr>
{% endfor %}
<tbody>
</table>
<h1>主机列表(字典)</h1>
<table border="1">
<thead>
<tr>
<th>主机名</th>
<th>ip地址</th>
<th>端口</th>
<th>业务线名称</th>
</tr>
</thead>
<tbody>
{% for row in v1 %}
<tr ht-d="{{ row.nid }}" b-id="{{ row.b.id }}">
<th>{{ row.hostname }}</th>
<th>{{ row.ip }}</th>
<th>{{ row.port }}</th>
<th>{{ row.b.caption }}</th>
</tr>
{% endfor %}
<tbody>
</table>
<h1>业务线列表*(元组)</h1>
<table border="1">
<thead>
<tr>
<th>主机名</th>
<th>ip地址</th>
</tr>
</thead>
<tbody>
{% for row in v3 %}
<tr ht-d="{{ row.0 }}" b-id="{{ row.2 }}">
<th>{{ row.1 }}</th>
<th>{{ row.3 }}</th>
</tr>
{% endfor %}
<tbody>
</table>
</body>
</html>
第20周-09 增加一对多数据示例; --添加主机--用模态对话框演示:
接上面:
app01/views.py
from django.shortcuts import render,HttpResponse,redirect
# Create your views here.
from app01 import models
def business(request):
v1=models.Business.objects.all()
# for row in v1:
# print(row.id,row.caption)
v2=models.Business.objects.values('id','caption')
# for row in v2:
# print(row['id'],row['caption'])
#[{'id':'1','caption':'运维','code':'sa'}] values 是个字典
v3=models.Business.objects.values_list('id','caption')
#[(1,运维),(2,市场)] values_list 是个元组
return render(request,'business.html',{'v1':v1,'v2':v2,'v3':v3})
#return HttpResponse('ok')
def host(request):
if request.method=='GET':
b_list=models.Business.objects.all()
elif request.method=='POST':
h=request.POST.get('hostname')
i=request.POST.get('ip')
p=request.POST.get('port')
b=request.POST.get('b_id')
models.Host.objects.create(hostname=h,ip=i,port=p,b_id=b)
return redirect('/host/')
v1=models.Host.objects.filter(nid__gt=0)
# for row in v1:
# print(row.nid,row.hostname)
v2=models.Host.objects.filter(nid__gt=0).values('nid','hostname','b_id','b__caption')
# for row in v2:
# print(row['nid'],row['hostname'],row['b_id'])
v3=models.Host.objects.filter(nid__gt=0).values_list('nid','hostname','b_id','b__caption')
# for row in v3:
# print(row[0],row[1])
#return HttpResponse('ok')
return render(request,'host.html',{'v1':v1,'v2':v2,'v3':v3,'b_list':b_list})
templates/host.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.hide {
display: none;
}
.shade {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: black;
opacity: 0.6;
z-index: 100;
}
.add-modal {
position: fixed;
height: 300px;
width: 400px;
top: 100px;
left: 50%;
z-index: 101;
border: 1px solid red;
background: white;
margin-left: -200px;
}
</style>
</head>
<body>
<h1>主机列表(列表)</h1>
<div>
<input id="add_host" type="button" value="添加">
</div>
<table border="1">
<thead>
<tr>
<th>序号</th>
<th>主机名</th>
<th>ip地址</th>
<th>端口</th>
<th>业务线名称</th>
</tr>
</thead>
<tbody>
{% for row in v1 %}
<tr ht-d="{{ row.nid }}" b-id="{{ row.b.id }}">
<th>{{ forloop.counter }}</th>
<th>{{ row.hostname }}</th>
<th>{{ row.ip }}</th>
<th>{{ row.port }}</th>
<th>{{ row.b.caption }}</th>
</tr>
{% endfor %}
<tbody>
</table>
<h1>主机列表(字典)</h1>
<table border="1">
<thead>
<tr>
<th>主机名</th>
<th>ip地址</th>
<th>端口</th>
<th>业务线名称</th>
</tr>
</thead>
<tbody>
{% for row in v1 %}
<tr ht-d="{{ row.nid }}" b-id="{{ row.b.id }}">
<th>{{ row.hostname }}</th>
<th>{{ row.ip }}</th>
<th>{{ row.port }}</th>
<th>{{ row.b.caption }}</th>
</tr>
{% endfor %}
<tbody>
</table>
<h1>主机列表*(元组)</h1>
<table border="1">
<thead>
<tr>
<th>主机名</th>
<th>ip地址</th>
</tr>
</thead>
<tbody>
{% for row in v3 %}
<tr ht-d="{{ row.0 }}" b-id="{{ row.2 }}">
<th>{{ row.1 }}</th>
<th>{{ row.3 }}</th>
</tr>
{% endfor %}
<tbody>
</table>
<div class="shade hide"></div>
<div class="add-modal hide">
<form method="post" action="/host/">
<div class="group">
<input type="text" placeholder="主机名" name="hostname">
</div>
<div class="group">
<input type="text" placeholder="IP" name="ip">
</div>
<div class="group">
<input type="text" placeholder="端口" name="port">
</div>
<div class="group">
<select name="b_id">
{% for op in b_list %}
<option value="{{ op.id }}">{{ op.caption }}</option>
{% endfor %}
</select >
<input type="submit" value="提交">
<input id="cancle" type="button" value="取消">
</div>
</form>
</div>
<script src="/static/jquery-3.2.1.js"></script>
<script>
$(function () {
$('#add_host').click(function () {
$('.add-modal,.shade').removeClass('hide');
});
$('#cancle').click(function(){
$('.add-modal,.shade').addClass('hide');
})
})
</script>
</body>
</html>