Pyhton学习——Day58
From表单验证
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form id="fm" action="/f1.html" method="POST"> <p>{{ obj.user }}{{ obj.errors.user.0 }}</p> <p>{{ obj.pwd }}{{ obj.errors.pwd.0 }}</p> <p>{{ obj.age }}{{ obj.errors.age.0 }}</p> <p>{{ obj.email }}{{ obj.errors.email.0 }}</p> <p><input type="submit" value="提交"/></p> <p><input type="button" value="Ajax提交" onclick="submitAjaxForm();"/></p> </form> <script src="/static/jquery-3.1.1.js"></script> <script> function submitAjaxForm() { $.ajax({ url:'/f1.html', type:'POST', data:$('#fm').serialize(), success:function (arg) { console.log(arg); } }) } </script> </body> </html>
from django.shortcuts import render,HttpResponse,redirect from django import forms from django.forms import fields # Create your views here. class F1Form(forms.Form): user = fields.CharField(max_length=18, min_length=6, required=True, error_messages={ 'required':'用户名不能为空', }) pwd = fields.CharField(min_length=32, required=True) age = fields.IntegerField( required=True, error_messages={ 'invalid':'必须为数字格式', 'required':'年龄不能为空' } ) email = fields.EmailField( required=True, error_messages={ 'invalid':'必须为邮件格式,带@的那种', 'required': '邮箱不能为空' } ) def f1(request): if request.method =='GET': obj = F1Form() return render(request,'f1.html',{'obj':obj}) else: # u = request.POST.get('user') #不能为空,长度6-18 # p = request.POST.get('pwd') #不能为空 # e = request.POST.get('email') #邮箱格式 # a = request.POST.get('age') #不能为空,必须为数字类型 # # #1.检查是否为空 # #2.检查格式是否正确 # print(u,p,e,a) obj = F1Form(request.POST) #是否验证成功 if obj.is_valid(): #已经验证过的数据 print('验证成功',obj.cleaned_data) return redirect('http://www.baidu.com') else: print('验证失败',obj.errors) return render(request,'f1.html',{'obj':obj})
"""day58 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from django.conf.urls import url from app01 import views from app02 import views as v2 urlpatterns = [ path('admin/', admin.site.urls), url(r'^index.html$',views.index), url(r'^index1.html$', views.index1), url(r'^f1.html$', v2.f1), ]
Win a contest, win a challenge
posted on 2018-04-21 10:53 pandaboy1123 阅读(225) 评论(0) 编辑 收藏 举报