Model常用操作:
- 参数:filter
- all,values,values_list
[obj(id,name,pwd,email),obj(id,name,pwd,email),]
models.UserInfo.objects.all()
[obj(id,name,email)] # pwd未取值
data_list = models.UserInfo.objects.all().only(‘name‘,‘email‘)
for item in data_list:
item.id
item.name
[obj(id,pwd)] # pwd未取值
data_list = models.UserInfo.objects.all().defer(‘name‘,‘email‘)
for item in data_list:
item.id
item.pwd
路由系统:
反向生成URL:
/index/ func name=a1
{% url "a1"}
reverse(‘x‘)
/index/(\d+)/ func name=a2
{% url "a2" 11 %}
reverse(‘x‘,args=(11,))
/index/(?P<nid>\d+)/ func name=a3
{% url "a2" nid=11 %}
reverse(‘x‘,kwargs={‘nid‘:11})
Django生命周期:
- wsgi
- wsgiref
- uwsgi
Http请求本质:
a1=123&a2=456
{a1:13}
今日概要:
1. 数据库设计
- 属性相同归类到一张表中
- 连表有性能消耗
- 连表设计:
class UserType(models.Model):
"""
用户类型表,个数经常变动
"""
title = models.CharField(max_length=32)
class UserInfo(models.Model):
"""
用户表:讲师和班主任
"""
username = models.CharField(max_length=32)
password = models.CharField(max_length=64)
email = models.CharField(max_length=32)
ut = models.ForeignKey(to="UserType")
- choices
# class UserInfo(models.Model):
# """
# 用户表
# """
# username = models.CharField(max_length=32)
# password = models.CharField(max_length=64)
# email = models.CharField(max_length=32)
#
# user_type_choices = (
# (1, ‘班主任‘),
# (2, ‘讲师‘),
# )
#
# user_type_id = models.IntegerField(choices=user_type_choices)
- 一张表中对同一个其他表做FK,M2M时,主要 related_name
- 注释
- 补充:
"""
ID Title
1 图片
2 挨踢1024
3 段子
"""
class NewsType(models.Model):
title = models.CharField(max_length=32)
"""
ID Title Summary News_Type
1 t.... 科技... 2
2 t.... 科技... 1
3 t.... 科技... 2
"""
class News(models.Model):
title = models.CharField(max_length=32)
summary = models.CharField(max_length=255)
news_type = models.ForeignKey(to="NewsType")
# 查看所有新闻
new_list = News.objects.all()
for row in new_list:
print(row.title,row.summary,row.news_type.title)
"""
ID Title Summary News_Type
1 t.... 科技... 2
2 t.... 科技... 1
3 t.... 科技... 2
"""
class News(models.Model):
title = models.CharField(max_length=32)
summary = models.CharField(max_length=255)
news_type_chices = (
(1,‘图片‘),
(2,‘挨踢1024‘),
(3,‘段子‘),
)
news_type = models.IntegerField(choices=news_type_chices)
# 查看所有新闻
new_list = News.objects.all()
for row in new_list:
print(row.title,row.summary, row.get_news_type_display() )
2. 登录
- 装饰器
- Django内置+自定义配置文件
3. 老师管理
- Form组件
- 创建类,继承Form
- 创建字段,字段=正则表达式; PS: 字段名称,required, error_messages = {required,invalid}
- form = MyForm(data=request.POST)
- form.is_valid()
- form.cleaned_data
- form.errors
Form组件
1. 用户请求数据验证
2. 自动生成错误信息
3. 打包用户提交正确信息
4. 错误:保留上次输入内容
5. 定制页面上显示的HTML标签
Django Form组件
1. 创建规则(类,字段)
class Foo:
username = xxx
password = xxx
email = xxx
2. 数据和规则进行匹配
form = Foo(data=xxx,initial=初始化)
form.is_valid()
form.cleaned_data
form.errors
class TeacherForm(Form): username = fields.CharField( required=True, error_messages={‘required‘:‘用户名不能为空‘}, widget=widgets.TextInput(attrs={‘placeholder‘:‘用户名‘,‘class‘:‘form-control‘}) ) # 不能为空 password = fields.CharField(required=True,error_messages={‘required‘:‘密码不能为空‘}, widget=widgets.TextInput(attrs={‘placeholder‘:‘密码‘,‘class‘:‘form-control‘})) # 不能为空 email = fields.EmailField(required=True,error_messages={‘required‘:‘邮箱不能为空‘,‘invalid‘:‘邮箱格式错误‘},widget=widgets.EmailInput(attrs={‘placeholder‘:‘邮箱‘,‘class‘:‘form-control‘})) # 不能为空,且邮箱格式 @auth def add_teacher(request): if request.method == ‘GET‘: form = TeacherForm() return render(request,‘add_teacher.html‘,{‘form‘:form}) else: """ 1. 用户请求数据验证 2. 自动生成错误信息 3. 打包用户提交正确信息 4. 错误:保留上次输入内容 5. 定制页面上显示的HTML标签 Django Form组件 1. 创建规则(类,字段) class Foo: username = xxx password = xxx email = xxx 2. 数据和规则进行匹配 """ form = TeacherForm(data=request.POST) # 数据和规则放置一起 if form.is_valid(): # 开始校验,并获取校验结果 # print(‘执行成功‘,form.cleaned_data) # 所有匹配成功,字典 # {‘username‘: ‘asd‘, ‘password‘: ‘sdf‘, ‘email‘: ‘[email protected]‘,‘ut_id‘:1} form.cleaned_data[‘ut_id‘] = 1 models.UserInfo.objects.create(**form.cleaned_data) return redirect(‘/teachers/‘) return render(request, ‘add_teacher.html‘,{‘form‘:form}) @auth def edit_teacher(request,nid): obj = models.UserInfo.objects.filter(id=nid,ut_id=1).first() if not obj: return redirect(‘/teachers/‘) if request.method == "GET": # 显示input,并且将数据库中的默认值填写到input框中 form = TeacherForm(initial={‘username‘:obj.username,‘password‘:obj.password,‘email‘:obj.email}) return render(request,‘edit_teacher.html‘,{‘form‘:form}) else: form = TeacherForm(data=request.POST) if form.is_valid(): # 校验成功 models.UserInfo.objects.filter(id=nid).update(**form.cleaned_data) return redirect(‘/teachers/‘) return render(request,‘edit_teacher.html‘,{‘form‘:form}) class TestForm(Form): caption = fields.CharField() # xxx = fields.ChoiceField(choices=[(1,‘讲师‘),(2,‘班主任‘)]) # xxx = fields.ChoiceField(choices=models.UserInfo.objects.values_list(‘id‘,‘username‘)) # xxx = fields.ChoiceField(choices=models.UserType.objects.values_list(‘id‘,‘title‘)) xxx = fields.MultipleChoiceField(choices=models.UserInfo.objects.values_list(‘id‘,‘username‘)) def test(request): form = TestForm(initial={‘xxx‘:4}) form = TestForm(initial={‘xxx‘:[1,2,3]}) return render(request,‘test.html‘,{‘form‘:form})
试用