跟b站武沛齐老师的视频学习 对学习过程进行一些记录以便复习 同时自我督促 :D冲鸭
视频链接: 15天django入门到放弃-哔哩哔哩.
练习题
男女生分别建表
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=64)
class Girl(models.Model):
nickname = models.CharField(max_length=32)
username = models.CharField(max_length=32)
password = models.CharField(max_length=64)
class B2G(models.Model):
b = models.ForeignKey(to='Boy', on_delete=models.DO_NOTHING)
g = models.ForeignKey(to='Girl', on_delete=models.DO_NOTHING)
urls.py :
from django.contrib import admin
from django.urls import path, re_path
from app01.views import account, love
urlpatterns = [
path('admin/', admin.site.urls),
re_path('^login.html/', account.login),
re_path('^logout.html/', account.logout),
re_path('^index.html/', love.index),
re_path('^others.html/', love.others),
]
account.py :
from django.shortcuts import render, redirect, HttpResponse
from app01 import models
def login(request):
if request.method == 'GET':
return render(request, 'login.html')
else:
username = request.POST.get('username')
password = request.POST.get('password')
gender = request.POST.get('gender')
print(username, password, gender)
rmb = request.POST.get('rmb')
if gender == '1':
obj = models.Boy.objects.filter(username=username, password=password).first()
else:
obj = models.Girl.objects.filter(username=username, password=password).first()
if not obj:
return render(request, 'login.html', {'msg': '用户名或密码错误'})
else:
request.session['user_info'] = {
'user_id': obj.id,
'gender': gender,
'username': username,
'nickname': obj.nickname
}
return redirect('/index.html/')
def logout(request):
request.session.clear()
return redirect('/login.html/')
love.py :
from django.shortcuts import render, redirect, HttpResponse
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()
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':
userlist = models.B2G.objects.filter(b_id=current_user_id).values('g__nickname')
else:
userlist = models.B2G.objects.filter(g_id=current_user_id).values('b__nickname')
return render(request, 'others.html', {'user_list': userlist})
login.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>登录界面</h1>
<form method="POST" action="/login.html/">
{% csrf_token %}
<p>用户:<input type="text" name="username"></p>
<p>密码:<input type="text" 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="11">一个月免登录
</p>
<p><input type="submit" value="提交"></p>
{{ msg }}
</form>
</body>
</html>
index.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>当前用户:{{ request.session.user_info.nickname }}</h1>
<a href="/logout.html">注销</a>
<h3>异性列表</h3>
<ul>
{% for row in user_list %}
<li>{{ row.nickname }}</li>
{% endfor %}
</ul>
</body>
</html>
others.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>当前用户:{{ request.session.user_info.nickname }}</h1>
<a href="/logout.html">注销</a>
<h3>有关系的异性列表</h3>
<ul>
{% for row in user_list %}
{% if row.g__nickname %}
<li>{{ row.g__nickname }}</li>
{% else %}
<li>{{ row.b__nickname }}</li>
{% endif %}
{% endfor %}
</ul>
</body>
</html>
男女生合并为一张表
class UserInfo(models.Model):
nickname = models.CharField(max_length=32)
username = models.CharField(max_length=32)
password = models.CharField(max_length=64)
gender_choices = (
(1, '男'),
(2, '女'),
)
gender = models.IntegerField(choices=gender_choices)
反向关联使用 related_query_name :
class U2U(models.Model):
g = models.ForeignKey('UserInfo', related_query_name='a', on_delete=models.DO_NOTHING)
b = models.ForeignKey('UserInfo', related_query_name='b', on_delete=models.DO_NOTHING)
或 related_name :
class U2U(models.Model):
g = models.ForeignKey('UserInfo', related_name='a', on_delete=models.DO_NOTHING)
b = models.ForeignKey('UserInfo', related_name='b', on_delete=models.DO_NOTHING)
related 的应用例子:
class UserType(models.Model):
title = models.CharField(max_length=32)
class User(models.Model):
username = models.CharField(max_length=32)
ut = models.ForeignKey('UserType', related_name='xxxx')
U2U 表新增数据的两种方式:
def test(request):
models.U2U.objects.create(b_id=2, g_id=6)
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)
U2U查找关联对象的方式:
def test(request):
lb = models.UserInfo.objects.filter(id=1).first()
result = lb.girls.all()
for u in result:
print(u.g.nickname)
return HttpResponse('ok')
补充自关联
class UserInfo(models.Model):
nickname = models.CharField(max_length=32)
username = models.CharField(max_length=32)
password = models.CharField(max_length=64)
gender_choices = (
(1, '男'),
(2, '女'),
)
gender = models.IntegerField(choices=gender_choices)
m = models.ManyToManyField('UserInfo')
查找:
obj = models.UserInfo.objects.filter(id=1).first()
obj.m => select xx from xx where from_userinfo_id = 1
obj.userinfo_set => select xx from xx where to_userinfo_id = 1
obj = models.UserInfo.objects.filter(id=1).first()
obj.m.all()
obj = models.UserInfo.objects.filter(id=4).first()
obj.userinfo_set.all()
应用:多级评论
class Comment(models.Model):
new_id = models.IntegerField()
content = models.CharField(max_length=32)
user = models.CharField(max_length=32)
reply = models.ForeignKey('Comment', null=True, blank=True)
中间件
p124 130-133(没看)
WSGI
Django 生命周期:
MVC,MTV
models(数据库,模型) views(html模板)=> templates controllers(业务逻辑处理)=> views
Form组件
Form 验证 ?- 需要对请求数据做验证 ?- 获取到数据然后进行验证 ???- login: ?????邮箱正则 ???- register: ?????邮箱正则
问题: ?- 无法记住上次提交内容,刷新页面数据消失 ?- 重复进行用户数据校验:正则,长度,是否为空 ?
Django 提供 Form 组件:
?1. 定义规则 ??from django.forms import Form, fields ??class xxx(Form): ????xx = fields.CharField(required=True, max_length…, error_message=…)
?2. 使用 ??obj = xxx(request.POST) ??# 是否校验成功 ??v = obj.is_valid() # 根据字段名称匹配 html 标签 name 属性 = Form 类字段名 ??# 所有错误信息 ??obj.errors ??# 正确信息 ??obj.cleaned_data
views.py :
from django.shortcuts import render, redirect
from django.forms import Form, fields
class LoginForm(Form):
username = fields.CharField(
max_length=18,
min_length=6,
required=True,
error_messages={
'required': '用户名不能为空',
'min_length': '太短了',
'max_length': '太长了',
}
)
password = fields.CharField(min_length=16, required=True)
def login(request):
if request.method == "GET":
return render(request,'login.html')
else:
obj = LoginForm(request.POST)
if obj.is_valid():
print(obj.cleaned_data)
else:
print(obj.errors['username'][0])
print(obj.errors['password'][0])
return render(request, 'login.html', {'obj': obj})
login.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="POST" action="/login/">
{% csrf_token %}
<p>
用户:<input type="text" name="username"> {{ obj.errors.username.0 }}
</p>
<p>
密码:<input type="password" name="password"> {{ obj.errors.password.0 }}
</p>
<input type="submit" value="提交">
{{ msg }}
</form>
</body>
</html>
|