上传文件 JSONP 输入框验证
一、上传文件
1.1、form上传
---------------------url from django.contrib import admin from django.urls import path from app import views urlpatterns = [ path('admin/', admin.site.urls), path('upload.html/', views.upload), ] -------------------upload.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post" action="/upload.html/" enctype="multipart/form-data"> <input type="text" name="user"> <input type="file" name="fafafa"> <input type="submit" value="提交"> </form> <div> {% for item in img_list %} <img style="height: 200px;width: 200px" src="/{{ item.path }}"> {% endfor %} </div> </body> </html> -------------------------views.py def upload(request): if request.method == 'GET': img_list = models.Img.objects.all() return render(request,'upload.html',{'img_list':img_list}) elif request.method == 'POST': user = request.POST.get('user') fafafa = request.POST.get('fafafa') # 获取文件名称 print(user,fafafa) obj = request.FILES.get('fafafa') # 获取文件内容 print(obj,obj.name,obj.size) # 文件 ,文件名 , 文件大小 # 传输文件 file_path = os.path.join('static','upload',obj.name) f = open(file_path, 'wb') # 上传文件路径 如果保存的数据库,保存的是路径 for chunk in obj.chunks(): f.write(chunk) f.close() print(user, fafafa) models.Img.objects.create(path=file_path) # 存储文件的路径到数据库 return render(request,'upload.html') --------------------models.py class Img(models.Model): path = models.CharField(max_length=128)
1.2、AJAX上传(FormData)
-------------------------url from django.contrib import admin from django.urls import path from app import views urlpatterns = [ path('admin/', admin.site.urls), path('upload.html/', views.upload), path('upload.html/upload.html/', views.upload), ] -----------------------upload.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .container img{ height: 300px; width: 300px; } </style> </head> <body> <div class="container"> {% for img in img_list %} <img src="/{{ img.path }}"> {% endfor %} </div> <input type="file" id="img"> <input type="button" value="提交" onclick="Upload()"> <script> function Upload() { // 创建FormData(),接受文件数据 var dic = new FormData(); // dic.append('user','v1'); dic.append('fafafa',document.getElementById('img').files[0]); // 发送文件数据 var xml = new XMLHttpRequest(); xml.open('post','upload.html/',true); xml.send(dic); } </script> </body> </html> --------------------------views.py from django.shortcuts import render,redirect,HttpResponse import os from app import models def upload(request): if request.method == 'GET': img_list = models.Img.objects.all() return render(request,'upload.html',{'img_list':img_list}) elif request.method == 'POST': obj = request.FILES.get('fafafa') # 获取文件内容 print(obj,obj.name,obj.size) # 文件 ,文件名 , 文件大小 # 传输文件 file_path = os.path.join('static','upload',obj.name) f = open(file_path, 'wb') # 上传文件路径 如果保存的数据库,保存的是路径 for chunk in obj.chunks(): f.write(chunk) f.close() models.Img.objects.create(path=file_path) # 存储文件的路径到数据库 return render(request,'upload.html') ----------------------models.py from django.db import models class Img(models.Model): path = models.CharField(max_length=128)
--------------------------url from django.contrib import admin from django.urls import path from app import views urlpatterns = [ path('admin/', admin.site.urls), path('upload.html/', views.upload), path('upload.html/upload.html/', views.upload), ] -------------------------views.py from django.shortcuts import render,redirect,HttpResponse import os from app import models import json def upload(request): if request.method == 'GET': img_list = models.Img.objects.all() return render(request,'upload.html',{'img_list':img_list}) elif request.method == 'POST': obj = request.FILES.get('fafafa') # 获取文件内容 print(obj,obj.name,obj.size) # 文件 ,文件名 , 文件大小 # 传输文件 file_path = os.path.join('static','upload',obj.name) f = open(file_path, 'wb') # 上传文件路径 如果保存的数据库,保存的是路径 for chunk in obj.chunks(): f.write(chunk) f.close() models.Img.objects.create(path=file_path) # 存储文件的路径到数据库 ret = {'status':True,'path':file_path} return HttpResponse(json.dumps(ret)) # python字符串装换成JSON字符串 返回ret -------------------------------upload.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .container img{ height: 300px; width: 300px; } </style> </head> <body> <div class="container" id="imgs"> {% for img in img_list %} <img src="/{{ img.path }}"> {% endfor %} </div> <input type="file" id="img"> <input type="button" value="提交" onclick="Upload()"> <script> function Upload() { // 创建FormData(),接受文件数据 var dic = new FormData(); // dic.append('user','v1'); dic.append('fafafa',document.getElementById('img').files[0]); // 发送文件数据 var xml = new XMLHttpRequest(); xml.open('post','upload.html/',true); xml.onreadystatechange = function(){ if (xml.readyState == 4){ var obj = JSON.parse(xml.responseText); // parse转换成JSON对象 获取返回的ret if (obj.status){ // 返回 ret中的status = True var img = document.createElement('img'); img.src = '/' + obj.path; document.getElementById('imgs').appendChild(img); } } }; xml.send(dic); } </script> </body> </html> ------------------------models.py from django.db import models class Img(models.Model): path = models.CharField(max_length=128)
--------------------------url from django.contrib import admin from django.urls import path from app import views urlpatterns = [ path('admin/', admin.site.urls), path('upload.html/', views.upload), path('upload.html/upload.html/', views.upload), ] -------------------------views.py from django.shortcuts import render,redirect,HttpResponse import os from app import models import json def upload(request): if request.method == 'GET': img_list = models.Img.objects.all() return render(request,'upload.html',{'img_list':img_list}) elif request.method == 'POST': obj = request.FILES.get('fafafa') # 获取文件内容 print(obj,obj.name,obj.size) # 文件 ,文件名 , 文件大小 # 传输文件 file_path = os.path.join('static','upload',obj.name) f = open(file_path, 'wb') # 上传文件路径 如果保存的数据库,保存的是路径 for chunk in obj.chunks(): f.write(chunk) f.close() models.Img.objects.create(path=file_path) # 存储文件的路径到数据库 ret = {'status':True,'path':file_path} return HttpResponse(json.dumps(ret)) # python字符串装换成JSON字符串 返回ret -------------------------------upload.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .container img{ height: 300px; width: 300px; } </style> </head> <body> <div class="container" id="imgs"> {% for img in img_list %} <img src="/{{ img.path }}"> {% endfor %} </div> <input type="file" id="img"> <input type="button" value="提交" onclick="Upload()"> <input type="button" value="提交AJAX" onclick="Uploadjq()"> <script> function Upload() { // 创建FormData(),接受文件数据 var dic = new FormData(); // dic.append('user','v1'); dic.append('fafafa',document.getElementById('img').files[0]); // 发送文件数据 var xml = new XMLHttpRequest(); xml.open('post','upload.html/',true); xml.onreadystatechange = function(){ if (xml.readyState == 4){ var obj = JSON.parse(xml.responseText); // parse转换成JSON对象 获取返回的ret if (obj.status){ // 返回 ret中的status = True var img = document.createElement('img'); img.src = '/' + obj.path; document.getElementById('imgs').appendChild(img); } } }; xml.send(dic); } function Uploadjq() { // 创建FormData(),接受文件数据 var dic = new FormData(); dic.append('fafafa',document.getElementById('img').files[0]); $ajax({ url:'upload.html/', type:'POST', data:dic, processData:false, // dic图片数据不做处理,传输文件 contentType:false, dataType:JSON, success:function (arg) { // console.log(arg) if (arg.status){ var img = document.createElement('img'); img.src = '/' + arg.path; $('#imgs').append(img); } } }) } </script> </body> </html> ------------------------models.py from django.db import models class Img(models.Model): path = models.CharField(max_length=128)
1.3、iframe和form共同完成异步上传(iframe 功能:接受内容,并执行)
--------------------------url from django.contrib import admin from django.urls import path from app import views urlpatterns = [ path('admin/', admin.site.urls), path('upload.html/', views.upload), path('upload.html/upload.html/', views.upload), ] ------------------------views.py from django.shortcuts import render,redirect,HttpResponse import os from app import models import json def upload(request): if request.method == 'GET': img_list = models.Img.objects.all() return render(request,'upload.html',{'img_list':img_list}) elif request.method == 'POST': obj = request.FILES.get('fafafa') # 获取文件内容 print(obj,obj.name,obj.size) # 文件 ,文件名 , 文件大小 # 传输文件 file_path = os.path.join('static','upload',obj.name) f = open(file_path, 'wb') # 上传文件路径 如果保存的数据库,保存的是路径 for chunk in obj.chunks(): f.write(chunk) f.close() models.Img.objects.create(path=file_path) # 存储文件的路径到数据库 ret = {'status':True,'path':file_path} return HttpResponse(json.dumps(ret)) # python字符串装换成JSON字符串 返回ret -----------------------------models.py from django.db import models class Img(models.Model): path = models.CharField(max_length=128) ----------------------------upload.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .container img{ height: 300px; width: 300px; } </style> </head> <body> <div class="container" id="imgs"> {% for img in img_list %} <img src="/{{ img.path }}"> {% endfor %} </div> <h2> 测试iframe功能</h2> <input type="text" id="url"> <input type="button" value="点我" onclick="iframeChange()"> <iframe id="ifr" src=""></iframe> <h2>基于iframe实现提交</h2> <form action="/upload.html/" method="post" target="iframe_1" enctype="multipart/form-data"> <iframe id="iframe_1" name="iframe_1" src="" onload="loadiframe()" style="display: none" ></iframe> <input type="text" name="user"> <input type="file" name="fafafa"> <input type="submit" value="实现iframe"> </form> <script src="/static/jquery-2.1.4.min.js"></script> <script> function iframeChange() { var url = $('#url').val(); $('#ifr').attr('src',url); } function loadiframe() { console.log(1); // 获取iframe的内容 var str_json = $('#iframe_1').contents().find('body').text(); // contents 获取上下文(包含html页面时) obj = JSON.parse(str_json); if (obj.status) { var img = document.createElement('img'); img.src = '/' + obj.path; $('#imgs').append(img); } } </script> </body> </html>
二、JSONP
JSONP:实质就是通过一个触发事件->创建一个标签,该标签包含一个方法->当事件触发事件,就会执行已经存在的方法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="button" onclick="jsonpRequest()" value="跨域请求"> <script> // 1.创建一个方法,方法创建一个标签,标签内含有一个方法。当执行该方法时,标签内的方法就会自动执行 function jsonpRequest() { tag = document.createElement('script'); // tag.src = 'http://www.baidu.com'; pFun('执行pFun方法'); // 标签内包含的方法,调用jsonRequest()时,就会调用执行 document.head.appendChild(tag); document.head.removeChild(tag) } // 被执行的方法 function pFun(arg) { console.log(arg) } </script> </body> </html>
三、Django的form验证
Form表单的功能
- 自动生成HTML表单元素
- 检查表单数据的合法性
- 如果验证错误,重新显示表单(数据不会重置)
- 数据类型转换(字符类型的数据转换成相应的Python类型)
Form相关的对象包括
- Widget:用来渲染成HTML元素的工具,如:forms.Textarea对应HTML中的<textarea>标签(插件)
- Field:Form对象中的一个字段,如:EmailField表示email字段,如果这个字段不是有效的email格式,就会产生错误。(字段)
- Form:一系列Field对象的集合,负责验证和显示HTML元素
- Form Media:用来渲染表单的CSS和JavaScript资源。
Form 表单实现验证的步骤
步骤一: 用户提交数据的验证
1、创建模版 class LoginForm(forms.Form):...
2、将请求交给模版,创建一个对象 obj = LoginForm(request.POST)
3、进行验证 obj.is_valid()
4、获取正确信息 obj.clean()
5、获取错误信息 obj.errors
步骤二: 错误信息提示
Form提交,刷新页面的特性,模版对象内部值丰富,再显示时,值和错误信息都有
步骤三:保留上一次提交的数据
1、自动生成html标签
2、保留上一次提交的数据
实例:
---------------------url path('login.html/', views.login), path('index.html/', views.index), --------------------views from django.shortcuts import render,redirect,HttpResponse """def login(request): if request.method == 'GET': return render(request,'login.html') elif request.method == 'POST': u = request.POST.get('uname') e = request.POST.get('emil') p = request.POST.get('pwd') print(u,e,p) return render(request,'login.html')""" from django import forms class LoginForm(forms.Form): user = forms.CharField(max_length=14,min_length=6,error_messages={"required": '用户名不能为空','min_length': '用户名长度不能小6'}) email = forms.EmailField(error_messages={"required": '邮箱不能为空','invalid': '邮箱格式错误'}) class Indexfrom(forms.Form): user = forms.CharField(max_length=14, min_length=6,error_messages={"required": '用户名不能为空','min_length': '用户名长度不能小6'}) email = forms.EmailField(error_messages={"required": '邮箱不能为空','invalid': '邮箱格式错误'}) favor = forms.MultipleChoiceField( choices=[(1,'test1'),(2,'test2'),(3,'test3')] ) def login(request): if request.method == "GET": # 数据库中获取 obj = LoginForm() return render(request, 'login.html', {'oo': obj}) elif request.method == "POST": '''obj = LoginForm(request.POST) state = obj.is_valid() # 状态(布尔类型 True False) print(state) value_dict = obj.clean() # 成功信息 print(value_dict) error_obj = obj.errors() # 失败信息 print(error_obj) ''' obj = LoginForm(request.POST) if obj.is_valid(): value_dict = obj.clean() print(value_dict) # create(**value_dict) #成功数据添加到表中 else: pass return render(request, 'login.html', {'oo': obj})
def index(request):
# obj = Indexfrom
obj = Indexfrom({'user': 'root','email': 'root@live.com','favor': [2,3]}) # 设置默认值
return render(request,'index.html',{'obj':obj})
--------------------login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>Form提交数据</h1> <form method="POST" action="/login.html/"> <p> {{ oo.user }} <span>{{ oo.errors.user.0 }}</span> </p> <p> {{ oo.email }} <span>{{ oo.errors.email.0 }}</span> </p> <p> {{ oo.favor }} </p> <p> <input type="text" name="pwd" placeholder="密码" /> </p> <input type="submit" value="提交" /> {{ msg }} <input id="ajax_submit" type="button" value="Ajax提交" /> </form> </body>
form表单验证进阶
引入:( from django import forms
from django.forms import fields
from django.forms import widgets )
fields.CharField(widget=widgets.TextInput(attrs={'class':'c1','placeholder':'用户名'}))
类:模版,到底验证几个 ---> fields.CharField(widget=widgets.TextInput())
字段:用于验证用户某个字段 ---> CharField
CharField
IntegerField
IP,Email,URL,Slug
ChoiceField(简写) CharField+插件
MultipleChoiceField
RegexField
参数:
required=True,
initial="默认值", 默认值
validators=[RegexValidator(r'^[0-9]+$', '11111',code='f1'), RegexValidator(r'^159[0-9]+$', '2222',code='f2')], 自定义属性
error_messages={'required': '不能为空','f1': 'geshicuowu','f2': 'kajdlfkjasldf','max_length': 'taichangla'}, 错误提示
choices=[(),(),()] 选择框
插件:user = forms.CharField(..,widget=Input框)
widget =
TextInput(Input)
NumberInput(TextInput)
EmailInput(TextInput)
URLInput(TextInput)
PasswordInput(TextInput)
HiddenInput(TextInput)
Textarea(Widget)
DateInput(DateTimeBaseInput)
DateTimeInput(DateTimeBaseInput)
TimeInput(DateTimeBaseInput)
CheckboxInput
Select
NullBooleanSelect
SelectMultiple
RadioSelect
CheckboxSelectMultiple
FileInput
ClearableFileInput
MultipleHiddenInput
SplitDateTimeWidget
SplitHiddenDateTimeWidget
SelectDateWidget
类型转换:fields.IntegerField ---> 传输的值为number
用法:
user1 = fields.CharField()
user2 = fields.CharField(widget=widgets.TextInput)
user3 = fields.CharField(widget=widgets.TextInput(attrs={}))
-----------------------特殊------------------------
单值:
user4 = fields.CharField(widget=widgets.Select(attrs={},choices=[(),(),()]))
user4 = fields.ChoiceField(choices=[(),(),()],widget=widgets.Select)
多值:
user4 = fields.CharField(widget=widgets.MutipleSelect(attrs={},choices=[(),(),()]))
user4 = fields.MultipleChoiceField(widget=widgets.MutipleSelect(attrs={},choices=[(),(),()]))
实例:
--------------------------URL------------------------- from app import views urlpatterns = [ path('admin/', admin.site.urls), path('detail.html/', views.detail), path('field.html/', views.field), ] ------------------------detail.html------------ <html lang="en"> <style> .c1{ color: deeppink; background-color: cornflowerblue; } </style> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post"> {{ obj.user1 }} {{ obj.user2 }} {{ obj.user3 }} {{ obj.user4 }} {{ obj.user5 }} {{ obj.user6 }} {{ obj.user7 }} {{ obj.user8|safe }} {{ obj.user9 }} {{ obj.user10 }} <input type="submit" value="提交"> </form > </body> </html> -------------------------field.html <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form> {{ obj.user }} <!-- <label for="{{ obj.user.id_for_label }}">{{ obj.user.label }}</label> {{ obj.user.label_tag }} --> <input type="submit" value="按钮"> </form> </body> </html> -------------------------forms.py(创建类)-------------- from django import forms as DForms from django.forms import fields from django.forms import widgets class DetailForm(DForms.Form): user1 = fields.CharField(widget=widgets.TextInput(attrs={'class':'c1','placeholder':'用户名'})) user2 = fields.CharField(widget=widgets.PasswordInput(attrs={'class':'c1'})) user3 = fields.ChoiceField(choices=[(1,"shanghai"),(2,"beijin")]) user5 = fields.CharField(widget=widgets.Select(choices=[(1,"shanghai"),(2,"beijin")])) user6 = fields.IntegerField(widget=widgets.Select(choices=[(1, "shanghai"), (2, "beijin")])) # 转型 user7 = fields.IntegerField(widget=widgets.RadioSelect(choices=[(1, "shanghai"), (2, "beijin")])) user4 = fields.IntegerField() user8 = fields.URLField(initial="URL") user9 = fields.EmailField(initial="Email") user10 = fields.GenericIPAddressField(initial="IP") class FieldForm(DForms.Form): user = fields.CharField( # required=True # 默认值 required=False, label = "label名", initial="初始值", show_hidden_initial=True, ) -----------------------------views.py------------------ from django.shortcuts import render def detail(request): from app import forms # 导入app项目下forms文件 obj = forms.DetailForm(request.POST) # 调用forms中的DetailForm类 obj.is_valid() print(obj.clean()) return render(request,'detail.html',{'obj':obj}) def field(request): from app import forms # 导入app项目下forms文件 if request.method == "GET": obj = forms.FieldForm() # 调用forms中的FieldForm类 return render(request,'field.html',{'obj':obj}) else: obj = forms.FieldForm(request.POST) obj.is_valid() print(obj.clean()) print(obj.errors.as_json()) return render(request,'field.html',{'obj':obj})