Python全栈之路-Django(十二)
1 相亲网
1.1 需求分析
1 登录,基于Session,装饰器
2 数据表:
男生表:
id username password
女生表
id username password
男生女生关系表
id nid nid
3 功能:
登录页:
用户名:
密码:
性别:
一周免登录:checkbox
session[id]
session[xingbie]
查看异性列表:
session[xingbie]
查看与自己有染得异性姓名列表
1.2 简单示例:
urls.py
from django.conf.urls import url
from django.contrib import admin
from app01.views import account,love
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login.html/', account.login),
url(r'^index.html/', love.index),
url(r'^logout.html/', account.logout),
url(r'^others.html/', love.others),
]
app01.models.py
from django.db import models
class Boy(models.Model):
nickname = models.CharField(max_length=32)
username = models.CharField(max_length=32)
password = models.CharField(max_length=32)
class Girl(models.Model):
nickname = models.CharField(max_length=32)
username = models.CharField(max_length=32)
password = models.CharField(max_length=32)
class B2G(models.Model):
b = models.ForeignKey(to='Boy',to_field='id')
g = models.ForeignKey(to='Girl',to_field='id')
app01.views.account.py
#!/usr/bin/env python
# __Author__: "wanyongzhen"
# Date: 2017/7/6
from django.shortcuts import HttpResponse,render,redirect
from app01 import models
def login(request):
if request.method == 'GET':
return render(request,'login.html')
else:
user = request.POST.get('username')
pwd = request.POST.get('password')
gender = request.POST.get('gender')
rmb = request.POST.get('rmb')
# 性别判断
if gender == '1':
obj = models.Boy.objects.filter(username=user,password=pwd).first()
else:
obj = models.Girl.objects.filter(username=user,password=pwd).first()
if not obj:
# 未登录成功
return render(request,'login.html',{'msg':'用户名或密码错误'})
else:
# request.session['user_id'] = obj.id
# request.session['gender'] = gender
# request.session['username'] = user
# 大字典写法
request.session['user_info'] = {
'user_id': obj.id,
'gender': gender,
'username': user,
'nickname': obj.nickname
}
return redirect('/index.html/')
def logout(request):
# 删除Session 会删除数据库中的数据
# request.session.delete(request.session.session_key)
# 只删除Cookie 不会删除数据库中的数据
request.session.clear()
return redirect('/login.html/')
app01.views.love.py
#!/usr/bin/env python
# __Author__: "wanyongzhen"
# Date: 2017/7/6
from django.shortcuts import HttpResponse,render,redirect
from app01 import models
def index(request):
if not request.session.get('user_info'):
return redirect('/login.html')
else:
gender = request.session.get('user_info').get('gender')
if gender == '1':
user_list = models.Girl.objects.all()
return render(request, 'index.html', {'user_list': user_list})
else:
user_list = models.Boy.objects.all()
return render(request,'index.html', {'user_list': user_list})
def others(request):
"""
获取与当前用户有关系的异性
:param request:
:return:
"""
current_user_id = request.session.get('user_info').get('user_id')
gender = request.session.get('user_info').get('gender')
if gender == '1':
user_list = models.B2G.objects.filter(b_id=current_user_id).values('g__nickname')
else:
user_list = models.B2G.objects.filter(b_id=current_user_id).values('b__nickname')
return render(request, 'others.html',{'user_list': user_list})
templates.login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/login.html/" method="post">
{% csrf_token %}
<p>用户:<input type="text" name="username"></p>
<p>密码:<input type="password" name="password"></p>
<p>
性别:
男<input type="radio" name="gender" value="1">
女<input type="radio" name="gender" value="2">
</p>
<p><input type="checkbox" name="rmb" value="0">一个月免登陆</p>
<input type="submit" value="提交">{{ msg }}
</form>
</body>
</html>
templates.index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% include 'user_header.html' %}
<h3>异性列表</h3>
<a href="/others.html">和我有关系的异性</a>
<ul>
{% for user in user_list %}
<li>{{ user.nickname }}</li>
{% endfor %}
</ul>
</body>
</html>
templates.others.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% include 'user_header.html' %}
<h1>有关系的异性列表</h1>
<ul>
{% for user in user_list %}
<li>{{ user.b__nickname }}{{ user.g__nickname }}</li>
{% endfor %}
</ul>
</body>
</html>
templates.user_header.html
<h1>当前用户:{{ request.session.user_info.nickname }}</h1>
<a href="/logout.html">注销</a>
2 自关联related_name
urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^test/', views.test),
]
app01.models.py
from django.db import models
class UserInfo(models.Model):
nickname = models.CharField(max_length=32)
username = models.CharField(max_length=32)
password = models.CharField(max_length=32)
gender_choices = (
(1, '男'),
(2, '女'),
)
gender = models.IntegerField(choices=gender_choices)
# relate_query_name 反向关联别名,保留_set
# obj对象男.b_set.all()
# obj对象女.a_set.all()
# relate_name(推荐) 反向关联别名
# obj对象男.b.all()
# obj对象女.a.all()
class U2U(models.Model):
# g = models.ForeignKey('UserInfo', related_query_name='a')
# b = models.ForeignKey('UserInfo', related_query_name='b')
g = models.ForeignKey('UserInfo', related_name='boys')
b = models.ForeignKey('UserInfo', related_name='girls')
app01.views.py
from django.shortcuts import render, HttpResponse
from app01 import models
# Create your views here.
def test(request):
# models.U2U.objects.create(b_id=2, g_id=6)
# models.U2U.objects.create(b_id=1, g_id=6)
# models.U2U.objects.create(b_id=1, g_id=4)
# models.U2U.objects.create(b_id=1, g_id=5)
# boy = models.UserInfo.objects.filter(gender=1, id=2).first()
# girl = models.UserInfo.objects.filter(gender=2, id=6).first()
# models.U2U.objects.create(b=boy, g=girl)
xz = models.UserInfo.objects.filter(id=1).first()
result = xz.girls.all() # <QuerySet [<U2U: U2U object>, <U2U: U2U object>, <U2U: U2U object>]>
for u in result:
print(u.g.nickname)
return HttpResponse('...')
3 manytomany自关联
urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^test/', views.test),
]
app01.models.py
from django.db import models
class UserInfo(models.Model):
nickname = models.CharField(max_length=32)
username = models.CharField(max_length=32)
password = models.CharField(max_length=32)
gender_choices = (
(1, '男'),
(2, '女'),
)
gender = models.IntegerField(choices=gender_choices)
m = models.ManyToManyField('UserInfo')
app01.views.py
from django.shortcuts import render, HttpResponse
from app01 import models
# Create your views here.
def test(request):
# 查男生(正向操作)
# xz = models.UserInfo.objects.filter(id=1).first()
# u = xz.m.all() # <QuerySet [<UserInfo: UserInfo object>, <UserInfo: UserInfo object>, <UserInfo: UserInfo object>]>
# for row in u:
# print(row.nickname)
# 查女生(反向操作)
mr = models.UserInfo.objects.filter(id=4).first()
v = mr.userinfo_set.all()
for row in v:
print(row.nickname)
return HttpResponse('...')
4 ForeignKey自关联
class Comment(models.Model):
"""
评论表
"""
news_id = models.IntegerField() # 新闻ID
content = models.CharField(max_length=32) # 评论内容
user = models.CharField(max_length=32) # 评论者
reply = models.ForeignKey('Comment',null=True,blank=True,related_name='xxxx')
"""
新闻ID reply_id
1 1 别比比 root null
2 1 就比比 root null
3 1 瞎比比 shaowei null
4 2 写的正好 root null
5 1 拉倒吧 由清滨 2
6 1 拉倒吧1 xxxxx 2
7 1 拉倒吧2 xxxxx 5
"""
"""
新闻1
别比比
就比比
- 拉倒吧
- 拉倒吧2
- 拉倒吧1
瞎比比
新闻2:
写的正好
"""
5 中间件
m1.py
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
class Middle1(MiddlewareMixin):
def process_request(self, request):
print('m1.process_request')
# return HttpResponse('不要再往下执行了') # 这里返回值后,下面的中间件和函数将不会被执行
def process_response(self, request, response):
print('m1.process_response')
return response
class Middle2(MiddlewareMixin):
def process_request(self, request):
print('m2.process_request')
# return HttpResponse('不要再往下执行了') # 这里返回值后,下面的中间件和函数将不会被执行
def process_response(self, request, response):
print('m2.process_response')
return response
settings.py
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',
'm1.Middle1',
'm1.Middle2',
]