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‘) #通过only可以取到里面指定的数据 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 #如果only里没有这个字段可以.到但是最好不要这样取值因为是重新取值一次
路由系统: 反向生成URL:( url 三种方式) /index/ func name=a1 {% url "a1"}#这个放在HTML页面 reverse(‘x‘)# 这个放到views函数里面 /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})
这是url反向解析的另一种形式:
Django生命周期: - wsgi - wsgiref - uwsgi Http请求本质: a1=123&a2=456 如果POST方法发送数据,数据放在url里面也可以取到 {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 views代码:
from django.shortcuts import render,redirect,HttpResponse from django.conf import settings # Create your views here. from app01 import models def login(request): if request.method == "GET": return render(request,‘login.html‘) elif request.method =="POST": user = request.POST.get(‘user‘) pwd = request.POST.get(‘pwd‘) user = models.UserInfo.objects.filter(username=user,password=pwd).first() if not user: return render(request, ‘login.html‘,{‘msg‘:‘用户名或密码错误‘}) # request.session[‘user_info‘] = {‘id‘:user.id, ‘username‘:user.username} request.session[settings.SJF] = {‘id‘:user.id, ‘username‘:user.username} return redirect(‘/index/‘) else: return HttpResponse(‘滚‘) def auth(func): def inner(request,*args,**kwargs): user_info = request.session.get(settings.SJF) if not user_info: return redirect(‘/login/‘) return func(request,*args,**kwargs) return inner @auth def index(request): username = request.session[settings.SJF][‘username‘] return render(request,‘index.html‘,{‘username‘:username}) @auth def teachers(request): # models.UserInfo.objects.filter(ut__title=‘讲师‘) teacher_list = models.UserInfo.objects.filter(ut_id=1) return render(request,‘teachers.html‘,{‘teacher_list‘:teacher_list}) from django.forms import Form from django.forms import fields from django.forms import widgets 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})
时间: 2024-11-09 01:51:58