线下---复习day04---作业
1 学的不好的同学:用ajax提交一个json格式数据,返回一个json格式数据,console.log打印出来
2 通过ajax上传一个文件并保存起来,前端接收到,弹窗说上传成功
urls.py
from django.contrib import admin from django.urls import path from app01 import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.add), path('files/', views.files), ]
views.py
from django.shortcuts import render,HttpResponse # Create your views here. import json def add(request): if request.is_ajax(): json_dict = json.loads(request.body) print(json_dict) dic1 = {'msg':'you is very good'} return HttpResponse(json.dumps(dic1)) return render(request,'add.html') def files(request): if request.is_ajax(): myfile = request.FILES.get('myfile') from django.core.files.uploadedfile import InMemoryUploadedFile name = myfile.name with open(name,'wb') as f: for line in myfile: f.write(line) return render(request,'add.html')
add.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> {% load static %} <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body> <p>用户名:<input type="text" id="d1" value="joab"></p> <p>密码:<input type="text" id="d2" value="123"></p> <p>文件:<input type="file" id="d3"></p> <button id="d4">发送ajax请求</button> <button id="d5">发送ajax文件</button> </body> <script> $('#d4').click(function () { $.ajax({ url:'', type: 'post', data:JSON.stringify({'username':$('#d1').val(),'password':$('#d2').val()}), contentType:'application/json', success:function (data) { console.log(data) } }) }) $('#d5').on('click',function () { let formDataObj = new FormData(); formDataObj.append('myfile',$('#d3')[0].files[0]) $.ajax({ url:'/files/', type: 'post', data:formDataObj, contentType: false, processData:false, success:function (args) { alert('上传成功') } }) }) </script> </html>
3 大家都写的:
用ajax提交用户的注册信息(用户名,密码,确认密码,年龄)(json),form组件做认证,姓名要大于4,小于16,不能以sb开头和结尾,用户名如果存在,也不能存进去,密码(最大16位,最小4位),年龄,小于150,大于18岁,密码和确认密码要一致,校验通过,存到user表中,
urls.py
from django.contrib import admin from django.urls import path from app01 import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.register), ]
views.py
from django.shortcuts import render from app01.myforms import MyRegForm from app01 import models from django.http import JsonResponse # Create your views here. import json def register(request): form_obj = MyRegForm() if request.is_ajax(): back_dic = {'code': 1000, 'msg': ''} json_dict = json.loads(request.body) form_obj = MyRegForm(json_dict) print(json_dict) if form_obj.is_valid(): clean_data = form_obj.cleaned_data clean_data.pop('re_password') print(clean_data) #写入数据库 models.UserInfo.objects.create_user(**clean_data) else: back_dic['code'] = 2000 back_dic['msg'] = form_obj.errors return JsonResponse(back_dic) return render(request,'register.html',locals())
settings.py需要在配置文件中告诉django你要用UserInfo替代auth_user(******)
AUTH_USER_MODEL = 'app01.UserInfo'
modles.py给原生的user表加额外字段
from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class UserInfo(AbstractUser): age = models.IntegerField(verbose_name='年龄')
register.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body class="text-center"> <form id="myform"> <h1>注册</h1> {% for form in form_obj %} <p><label for="{{ form.auto_id }}">{{ form.label }}</label> {{ form }} <span style="color: red"></span> </p> {% endfor %} <input type="button" class="btn btn-primary" value="注册" id="id_commit"> </form> </body> <script> $('#id_commit').click(function () { $.ajax({ url:'', type:'post', data:JSON.stringify({'username':$('#id_username').val(),'password':$('#id_password').val(), 're_password':$('#id_re_password').val(),'age':$('#id_age').val() }), contentType:'application/json', success:function (args) { if (args.code==1000){ alert('注册成功') }else { console.log(args.msg) $.each(args.msg,function (index,obj) { let targetId = '#id_' + index; $(targetId).next().text(obj[0]).parent().addClass('has-error') }) } } }) }) </script> </html>
利用forms组件渲染,校检数据
app01下创建myforms.py
from app01 import models from django import forms class MyRegForm(forms.Form): username = forms.CharField(label='用户名', max_length=16, min_length=4, error_messages={ 'required': '用户名不能为空', 'max_length': '最大16位', 'min_length': '最小4位', }) password = forms.CharField(label='密码', max_length=16, min_length=4, error_messages={ 'required': '密码不能为空', 'max_length': '最大16位', 'min_length': '最小4位', }) re_password = forms.CharField(label='确认密码', max_length=16, min_length=4, error_messages={ 'required': '确认密码不能为空', 'max_length': '最大16位', 'min_length': '最小4位', }) age = forms.IntegerField(label='年龄', max_value=150, min_value=18, error_messages={ 'required': '年龄不能为空', 'max_value': '最大150岁', 'min_value': '最小18岁', }) # 局部钩子 def clean_username(self): username = self.cleaned_data.get('username') # 数据库中校检数据 is_exist = models.UserInfo.objects.filter(username=username) print(is_exist) if is_exist: self.add_error('username', '用户名已存在') return username # 全局钩子 def clean(self): password = self.cleaned_data.get('password') re_password = self.cleaned_data.get('re_password') if not password == re_password: self.add_error('re_pwd', '两次密码不一致') return self.cleaned_data
4 读一下forms执行流程
5 自己手动实现一个存文件的session,自定制一个session字典
urls.py
from django.contrib import admin from django.urls import path from app01 import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.my_seesion), ]
views.py
from django.shortcuts import render,HttpResponse from django.contrib.auth.models import auth from app01 import models # Create your views here. #随机字符串 def str1(): import hashlib import random res = '' for i in range(3): s1 = chr(random.randint(65, 90)) s2 = str(random.randint(0, 9)) res += random.choice([s1, s2]) print(res) m = hashlib.md5() m.update(res.encode('utf-8')) m.update('aaa'.encode('utf-8')) return m.hexdigest() def my_seesion(request): if request.method == 'POST': print(request.myseesion) username = request.POST.get('username') password = request.POST.get('password') user_obj = auth.authenticate(request,username=username,password=password) if user_obj: suijistr = str1() print(suijistr) request.myseesion['myseesionid'] = suijistr is_exist = models.MySession.objects.filter(username=username) if is_exist: models.MySession.objects.filter(username=username).update(val=suijistr) else: models.MySession.objects.create(username=username,mysessionid='mysessionid',val=suijistr) return HttpResponse('登录成功') else: return HttpResponse('登录失败') return render(request,'my_seesion.html')
my_seesion.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body class="text-center"> <form action="" method="post"> {% csrf_token %} username: <p><input type="text" name="username"></p> password: <p><input type="password" name="password"></p> <input type="submit" class="btn btn-primary" value="登录"> </form> </body> </html>
modles.py
from django.db import models # Create your models here. class MySession(models.Model): username = models.CharField(verbose_name='用户名',max_length=100) mysessionid = models.CharField(max_length=200) val = models.CharField(max_length=300)
app01下自定义中间件
mysession.py
from django.contrib.auth.models import auth from django.shortcuts import render,HttpResponse from app01 import models from django.utils.deprecation import MiddlewareMixin class MySession(MiddlewareMixin): def process_response(self,request,response): user_obj = models.MySession.objects.get(username=request.user) response.set_cookie('myseesionid',user_obj.val) return response def process_request(self,request): request.myseesion = {} llq = request.COOKIES.get('myseesionid') if llq: print(llq) fwq = models.MySession.objects.get(username=request.user) fwq = fwq.val if not llq == fwq: return HttpResponse('cookie不对') else: request.myseesion.update({'myseesionid':fwq})
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', 'app01.mysession.MySession', ]
6 敲一遍bbs项目