首页 > 代码库 > python day20
python day20
Form
- 验证
- 生成HTML标签
- (select标签的数据:来源于数据)
cookie
session
CSRF
Model:
一对多
# 1,CEO 2,CIO 3,COO
class UserType(models.Model):
name = models.CharField(max_lenght=32)
class UserInfo(models.Model):
name = models.CharField(max_lenght=32)
pwd = models.CharField(max_lenght=32)
user_type = models.ForignKey(‘UserType‘)
1、查询用户类是CEO所有用户
q = UserInfo.objects.filter(user_type__name=‘CEO‘)
QuerySet
[对象,]
q[0].name
q[0].pwd
q[0].user_type.name
2、
q = UserInfo.objects.filter(user_type__name=‘CEO‘).values(‘name‘,‘pwd‘,‘user_type__name‘)
q
[{‘name‘:‘xxx‘,‘pwd‘: ‘xxx‘,‘user_type__name‘:‘xxx‘}]
3、
q = UserInfo.objects.filter(user_type__name=‘CEO‘).value_list(‘name‘,‘pwd‘,‘user_type__name‘)
q
[(xx,xx,xx),]
补充:(select标签的数据:来源于数据)
choices = [
(1,‘CEO‘),
(2,‘COO‘)
]
choices = UserType.objects.all().value_list(‘id‘,‘name‘)
1.选择下接选项,创建表及数据
urls.py
from app01 import views
urlpatterns = [
url(r‘^admin/‘, admin.site.urls),
url(r‘^index/‘, view=views.index),
]
views.py
from django.shortcuts import render,HttpResponse
# Create your views here.
from django import forms
from app01 import models
class IndexForm(forms.Form):
c = [
(1,‘CEO‘),
(2,‘COO‘),
]
def index(request):
#创建数据
# for i in range(10):
# models.UserType.objects.create(caption=‘CE‘+str(i))
# c = models.UserType.objects.all().count()
form = IndexForm()
return render(request,‘index.html‘,{‘form‘:form})
models.py
from django.db import models
# Create your models here.
class UserType(models.Model):
caption = models.CharField(max_length=16)
class UserInfo(models.Model):
username = models.CharField(max_length=32)
pwd = models.CharField(max_length=32)
user_type = models.ForeignKey(‘UserType‘)
settings.py
INSTALLED_APPS = [
‘django.contrib.admin‘,
‘django.contrib.auth‘,
‘django.contrib.contenttypes‘,
‘django.contrib.sessions‘,
‘django.contrib.messages‘,
‘django.contrib.staticfiles‘,
‘app01‘
]
STATIC_URL = ‘/static/‘
STATICFILES_DIRS = (
os.path.join(BASE_DIR,‘static‘),
)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>Index</h1>
{{ form.user_type_id }}
</body>
</html>
python3 manage.py makemigrations
python3 manage.py migrate
访问
http://127.0.0.1:8000/index/
-------------------------------------------------------------------------------
页面创建数据
http://127.0.0.1:8000/add_user_type/?q=CEO #以?q=值 方式创建
urls.py
from app01 import views
urlpatterns = [
url(r‘^admin/‘, admin.site.urls),
url(r‘^index/‘, view=views.index),
url(r‘^add_user_type/‘,view=views.add_user_type),
]
views.py
from django.shortcuts import render,HttpResponse
# Create your views here.
from django import forms
from app01 import models
class IndexForm(forms.Form):
# c = [
# (1,‘CEO‘),
# (2,‘COO‘),
# ]
# 获取数据
c = models.UserType.objects.all().values_list(‘id‘,‘caption‘)
user_type_id = forms.IntegerField(widget=forms.Select(choices=c))
# pass
def index(request):
# for i in range(10):
# models.UserType.objects.create(caption=‘CE‘+str(i))
# c = models.UserType.objects.all().count()
form = IndexForm()
return render(request,‘index.html‘,{‘form‘:form})
def add_user_type(request):
q = request.GET.get(‘q‘, None)
if q:
models.UserType.objects.create(caption=q)
return HttpResponse(q)
models.py
from django.db import models
# Create your models here.
class UserType(models.Model):
caption = models.CharField(max_length=16)
class UserInfo(models.Model):
username = models.CharField(max_length=32)
pwd = models.CharField(max_length=32)
user_type = models.ForeignKey(‘UserType‘)
settings.py
INSTALLED_APPS = [
‘django.contrib.admin‘,
‘django.contrib.auth‘,
‘django.contrib.contenttypes‘,
‘django.contrib.sessions‘,
‘django.contrib.messages‘,
‘django.contrib.staticfiles‘,
‘app01‘
]
STATIC_URL = ‘/static/‘
STATICFILES_DIRS = (
os.path.join(BASE_DIR,‘static‘),
)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>Index</h1>
{{ form.user_type_id }}
</body>
</html>
添加数据并访问
http://127.0.0.1:8000/add_user_type/?q=CEO
http://127.0.0.1:8000/index/
---------------------------------
views.py
from django.shortcuts import render,HttpResponse
# Create your views here.
from django import forms
from app01 import models
class IndexForm(forms.Form):
# c = [
# (1,‘CEO‘),
# (2,‘COO‘)
# ]
c = models.UserType.objects.all().values_list(‘id‘,‘caption‘)
user_type_id = forms.IntegerField(widget=forms.Select(choices=c))
def __init__(self,*args, **kwargs):
# 父类构造方法:1、获取所有静态字段 2、fields = []
super(IndexForm, self).__init__(*args, **kwargs)
# print(self.fields[‘user_type_id‘].widget.choices)
self.fields[‘user_type_id‘].widget.choices = models.UserType.objects.all().values_list(‘id‘,‘caption‘)
def index(request):
# for i in range(10):
# models.UserType.objects.create(caption=‘CE‘+str(i))
# c = models.UserType.objects.all().count()
# print(c)
form = IndexForm()
from django.db.models import Q
"""
q1 = Q()
q1.connector = ‘OR‘
q1.children.append((‘id‘, 1))
q1.children.append((‘id‘, 2))
q1.children.append((‘id‘, 3))
# 1 CE0
# 2 CE1
# 3 CE2
obj = models.UserType.objects.filter(q1)
for item in obj:
print(item.id,item.caption)
"""
con = Q()
q1 = Q()
q1.connector = ‘OR‘
q1.children.append((‘id‘, 1))
q1.children.append((‘id‘, 2))
q1.children.append((‘id‘, 3))
q2 = Q()
q2.connector = ‘OR‘
q2.children.append((‘caption‘, ‘CE1‘))
q2.children.append((‘caption‘, ‘CE2‘))
con.add(q1, ‘AND‘)
con.add(q2, ‘AND‘)
obj = models.UserType.objects.filter(con)
for item in obj:
print(item.id,item.caption)
return render(request, ‘index.html‘, {‘form‘: form})
def add_user_type(request):
q = request.GET.get(‘q‘, None)
if q:
models.UserType.objects.create(caption=q)
return HttpResponse(q)
def add_boy(request):
boy = request.GET.get(‘v‘,None)
if boy:
models.Boy.objects.create(username=boy)
return HttpResponse(boy)
def add_girl(request):
girl = request.GET.get(‘v‘,None)
if girl:
models.Girl.objects.create(name=girl)
return HttpResponse(girl)
def boy_to_girl(request):
"""
########### 增加数据 ###########
# 获取一个女孩对象
g1 = models.Girl.objects.get(id=1)
# 获取一个男孩对象
b1 = models.Boy.objects.get(id=1)
# 利用对对多字段b将男孩和女孩建立关系
g1.b.add(models.Boy.objects.get(id=1))
g1.b.add(1)
bs = models.Boy.objects.all()
g1.b.add(*bs)
g1.b.add(*[1,2,3])
"""
"""
########### 查询数据 ###########
# 获取一个女孩对象
g1 = models.Girl.objects.get(id=1)
# 获取和当前女孩有关系的所有男孩
boy_list = g1.b.all()
print(boy_list)
"""
"""
# 删除第三张表中和女孩1关联的所有关联信息
g1 = models.Girl.objects.get(id=1)
g1.b.clear()
# 查询和女孩1关联所有男孩
g1 = models.Girl.objects.get(id=1)
boy_list = g1.b.all()
print(boy_list)
"""
"""
# 添加和女孩1和 男孩1,2,3,4关联
# g1 = models.Girl.objects.get(id=1)
# g1.b.add(*[1,2,3,4])
# 删除女孩1和男孩1的关联
g1 = models.Girl.objects.get(id=1)
g1.b.remove(1)
# 删除女孩1和男孩2,3的关联
g1 = models.Girl.objects.get(id=1)
g1.b.remove(*[2,3])
# 查询和女孩1关联所有男孩
g1 = models.Girl.objects.get(id=1)
boy_list = g1.b.all()
print(boy_list)
"""
#查三张表,联合查询
"""
r = models.Girl.objects.all().values(‘id‘,‘name‘,‘b__username‘)
models.Boy.objects.all().values(‘id‘,‘username‘,‘girl__name‘)
print(r)
print(r.query)
"""
"""
r = models.Boy.objects.all().values(‘id‘,‘username‘,‘girl__name‘)
print(r)
print(r.query)
"""
r = models.Girl.objects.filter(id=1).values(‘b‘)
print(r)
print(r.query)
return HttpResponse(‘ok‘)
中间件
md/sb.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# Author:Minghu Wang
from django.utils import deprecation
class M1(deprecation.MiddlewareMixin):
def process_request(self, request):
print(‘M1.process_request‘)
def process_response(self, request, response):
print(‘M1.process_response‘)
return response
class M2(deprecation.MiddlewareMixin):
def process_request(self, request):
print(‘M2.process_request‘)
def process_response(self, request, response):
print(‘M2.process_response‘)
return response
settings.py
MIDDLEWARE = [
‘md.sb.M1‘,
‘md.sb.M2‘,
‘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‘,
]
views.py
def md(request):
print(‘views.md‘)
return HttpResponse(‘ok‘)
views.py
from app01 import views
urlpatterns = [
url(r‘^admin/‘, admin.site.urls),
url(r‘^index/‘, view=views.index),
url(r‘^add_user_type/‘,view=views.add_user_type),
url(r‘^add_boy/‘,view=views.add_boy),
url(r‘^add_girl/‘,view=views.add_girl),
url(r‘^boy_to_girl/‘,view=views.boy_to_girl),
url(r‘^md/‘, views.md),
]
http://127.0.0.1:8000/md/
后台显示
M1.process_request
M2.process_request
views.md
M2.process_response
M1.process_response
python day20