Form验证实例
Posted leiwenbin627
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Form验证实例相关的知识,希望对你有一定的参考价值。
程序目录
models.py
from django.db import models
# Create your models here.
class UserInfo(models.Model):
user=models.CharField(max_length=32)
urls.py
"""s14_day22 URL Configuration
"""
from django.contrib import admin
from django.conf.urls import url
from app01 import views
urlpatterns = [
url(r‘^admin/‘, admin.site.urls),
url(r‘^login/$‘, views.login),
url(r‘^index/$‘, views.index),
url(r‘^logout/$‘, views.logout),
url(r‘^test_t/(\\d+)$‘, views.test_t),
url(r‘^cache/$‘, views.cache),
url(r‘^signal/$‘, views.signal),
url(r‘^fm/$‘, views.fm),
]
views.py
from django.shortcuts import render,redirect,HttpResponse
# Create your views here.
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‘)
if user=="root" and pwd=="123456":
#生成随机字符串
#写到用户浏览器cookie
#保存到session中
#在随机字符串对应的字典中设置相关内容。。。
#session中设置值
request.session[‘username‘]=user
request.session[‘is_login‘]=True
if request.POST.get(‘rmb‘,None)=="1":
#设置session超时时间 不设置 默认超时时间两周
request.session.set_expiry(10) #秒
return redirect("/index/")
else:
return render(request,‘login.html‘)
from django.views.decorators.csrf import csrf_exempt,csrf_protect
@csrf_exempt #不需要csrf认证
def index(request):
# 获取当前用户的随机字符串
# 根据随机字符串获取对应的信息
# session中获取值
if request.session.get(‘is_login‘,False):
return render(request,‘index.html‘,‘username‘:request.session[‘username‘])
else:
return HttpResponse(‘gun‘)
@csrf_protect #需要csrf认证
def logout(request):
request.session.clear()
return redirect(‘/login/‘)
class Foo:
def render(self):
return HttpResponse(‘ok‘)
def test_t(request,nid):
# int(‘111ed‘)
print("xiaoxima-->没带钱")
# return HttpResponse(‘ok‘)
return Foo()
from django.views.decorators.cache import cache_page
@cache_page(10) #10秒钟失效
def cache(request):
import time
ctime=time.time()
return render(request,‘cache.html‘,‘ctime‘:ctime)
def signal(request):
from app01 import models
obj=models.UserInfo(user=‘root‘)
print(‘end‘)
obj.save()
obj=models.UserInfo(user=‘lwb‘)
obj.save()
obj = models.UserInfo(user=‘alex‘)
obj.save()
from sg import pizza_done
pizza_done.send(sender="asasa",toppings=123,size=456)
return HttpResponse(‘ok‘)
#################Form#############################
from django import forms
from django.forms import widgets
from django.forms import fields
class FM(forms.Form):
#字段本身自己只做验证
#
user=fields.CharField(
error_messages=‘required‘:‘用户名不能为空‘,
widget=widgets.Textarea(attrs=‘class‘:‘c1‘),
label="用户名:",
# initial=‘root_xxpp‘
)
pwd=fields.CharField(
max_length=12,
min_length=6,
error_messages=‘required‘:‘密码不能为空‘,‘min_length‘:‘密码长度不能小于6‘,‘max_length‘:‘密码长度不能大于12‘,,
widget=widgets.PasswordInput(attrs=‘class‘:‘c2‘)
)
email=fields.EmailField(error_messages=‘required‘:‘邮箱不能为空‘,‘invalid‘:‘邮箱格式错误‘)
f=fields.FileField()
p=fields.FilePathField(path=‘app01‘)
city1=fields.MultipleChoiceField(
choices=[(0,‘上海‘),(1,‘广州‘),(2,‘清远‘)]
)
city2 = fields.ChoiceField(
choices=[(0, ‘上海‘), (1, ‘广州‘), (2, ‘清远‘)]
)
city3 = fields.MultipleChoiceField(
choices=((1,‘上海‘),(2,‘北京‘),),
initial=[1,],
widget=widgets.SelectMultiple
)
city4 = fields.CharField(
initial=2,
widget=widgets.Radioselect(choices=((1,‘清远‘),(2,‘深圳‘),))
)
from app01 import models
def fm(request):
if request.method=="GET":
# 从数据库中获取到数据
dic=
"user":"r1",
"pwd":"123123",
‘email‘:"[email protected]",
"city1": [1,2],
"city2":1,
obj=FM(initial=dic)
return render(request,‘fm.html‘,‘obj‘:obj)
elif request.method=="POST":
#获取用户所有的数据
#每条数据请求的验证
# 成功:获取所有的正确信息
# 失败:显示错误信息
obj=FM(request.POST)
r1=obj.is_valid()
if r1:
# print(obj.cleaned_data)
models.UserInfo.objects.create(**obj.cleaned_data)
else:
# ErrorDict
# print(obj.errors.as_json())
# print(obj.errors[‘user‘][0])
return render(request,‘fm.html‘,‘obj‘:obj)
return render(request,‘fm.html‘)
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/login/" method="post">
# % csrf_token %#
<input type="text" name="user">
<input type="password" name="pwd">
<input type="checkbox" name="rmb" value="1">10秒免登录
<input type="submit" value="提交">
<input id="btn1" type="button" value="按钮1">
<input id="btn2" type="button" value="按钮2">
</form>
<script src="/static/jquery-1.12.4.js"></script>
<script src="/static/jquery.cookie.js"></script>
<script>
$(function ()
# obj=XMLHttpRequest()#
# obj.open()#
# obj.send()#
# #
$.ajaxSetup(
beforeSend:function (xhr,settings)
xhr.setRequestHeader(‘X-CSRFtoken‘,csrftoken)
);
var csrftoken=$.cookie(‘csrftoken‘);
$(‘#btn1‘).click(function ()
$.ajax(
url:‘/login/‘,
type:"post",
data:‘user‘:‘root‘,‘pwd‘:‘123‘,
# headers:‘X-CSRFtoken‘:csrftoken,#
success:function (arg)
)
);
$(‘#btn2‘).click(function ()
$.ajax(
url:‘/login/‘,
type:"post",
data:‘user‘:‘root‘,‘pwd‘:‘123‘,
# headers:‘X-CSRFtoken‘:csrftoken,#
success:function (arg)
)
)
)
</script>
</body>
</html>
#xhr: xml http request对象#
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>欢迎登录: username -- request.session.username </h1>
<a href="/logout/">注销</a>
</body>
</html>
m1.py
from django.utils.deprecation import MiddlewareMixin
class Row1(MiddlewareMixin):
def process_request(self,request):
print(‘王生‘)
def process_view(self,request,view_func,view_func_args,view_func_kwargs):
print(‘张欣彤‘)
def process_response(self,request,response):
print(‘扛把子‘)
return response
from django.shortcuts import HttpResponse
class Row2(MiddlewareMixin):
def process_request(self,request):
print(‘陈毅强‘)
# return HttpResponse(‘走‘)
def process_view(self, request, view_func, view_func_args, view_func_kwargs):
print(‘张需要‘)
def process_response(self,request,response):
print(‘侯亚凡‘)
return response
class Row3(MiddlewareMixin):
def process_request(self,request):
print(‘刘冬‘)
def process_view(self,request,view_func,view_func_args,view_func_kwargs):
print(‘邵琳‘)
def process_response(self,request,response):
print(‘连之类‘)
return response
def process_exception(self,request,exception):
if isinstance(exception,ValueError):
return HttpResponse("出现异常了》。。。")
def process_template_response(self,request,response):
# 如果Views函数返回的对象中,具有render方法
print(‘----------------‘)
return response
settings.py
from django.middleware.csrf import CsrfViewMiddleware
MIDDLEWARE = [
‘django.middleware.cache.UpdateCacheMiddleware‘,#process_response 返回时 修改和保存获取到的数据到缓存里
‘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‘,
# ‘Middle.m1.Row1‘,
# ‘Middle.m1.Row2‘,
# ‘Middle.m1.Row3‘,
‘django.middleware.cache.FetchFromCacheMiddleware‘,#process_request 请求时 获取缓存
]
STATIC_URL = ‘/static/‘
STATICFILES_DIRS=(
os.path.join(BASE_DIR,‘static‘),
)
SESSION_SAVE_EVERY_REQUEST = True
# SESSION_ENGINE = ‘django.contrib.sessions.backends.db‘ # session保存到数据库引擎(默认)
# SESSION_ENGINE = ‘django.contrib.sessions.backends.cache‘ # session保存到缓存引擎
# SESSION_CACHE_ALIAS = ‘default‘
# SESSION_ENGINE = ‘django.contrib.sessions.backends.file‘ # session保存到文件引擎
# SESSION_FILE_PATH = os.path.join(BASE_DIR,‘save_session‘) # 缓存文件路径,如果为None,则使用tempfile模块获取一个临时地址tempfile.gettempdir() # 如:/var/folders/d3/j9tj0gz93dg06bmwxmhh6_xm0000gn/T
# SESSION_ENGINE = ‘django.contrib.sessions.backends.cached_db‘ # session保存到缓存+数据库
# SESSION_ENGINE = ‘django.contrib.sessions.backends.signed_cookies‘ # session保存到加密cookie
# CACHES =
# ‘db3‘:
# ‘BACKEND‘: ‘django.core.cache.backends.memcached.MemcachedCache‘,
# ‘LOCATION‘: ‘127.0.0.1:11211‘,
# ,
#
# ‘db1‘:
# ‘BACKEND‘: ‘django.core.cache.backends.memcached.MemcachedCache‘,
# ‘LOCATION‘: ‘unix:/tmp/memcached.sock‘,
# ,
#
# ‘db2‘:
# ‘BACKEND‘: ‘django.core.cache.backends.memcached.MemcachedCache‘,
# ‘LOCATION‘: [
# ‘172.19.26.240:11211‘,
# ‘172.19.26.242:11211‘,
# ]
#
#
CACHES =
‘default‘:
‘BACKEND‘: ‘django.core.cache.backends.filebased.FileBasedCache‘,
‘LOCATION‘: os.path.join(BASE_DIR,‘cache‘)
cache.html
% load cache %
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1> ctime </h1>
<h1> ctime </h1>
% cache 10 c1 %
<h1> ctime </h1>
% endcache %
</body>
</html>
sg.py
from django.core.signals import request_finished
from django.core.signals import request_started
from django.core.signals import got_request_exception
from django.db.models.signals import class_prepared
from django.db.models.signals import pre_init, post_init
from django.db.models.signals import pre_save, post_save
from django.db.models.signals import pre_delete, post_delete
from django.db.models.signals import m2m_changed
from django.db.models.signals import pre_migrate, post_migrate
from django.test.signals import setting_changed
from django.test.signals import template_rendered
from django.db.backends.signals import connection_created
def f1(sender, **kwargs):
print("f1oo_callback")
# print(sender, kwargs)
# def f2(sender, **kwargs):
# print("f2oo_callback")
# print(sender, kwargs)
pre_init.connect(f1)
# pre_init.connect(f2)
# xxoo.connect(callback)
# xxoo指上述导入的内容
import django.dispatch
pizza_done = django.dispatch.Signal(providing_args=["toppings", "size"])
def callback(sender, **kwargs):
print("callback")
print(sender, kwargs)
pizza_done.connect(callback)
fm.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/fm/" method="post">
% csrf_token %
<p> obj.user.label obj.user obj.errors.user.0 </p>
<p> obj.pwd obj.errors.pwd.0 </p>
<p> obj.email obj.errors.email.0 </p>
<p> obj.f obj.errors.f.0 </p>
# obj.p #
obj.city1
obj.city2
# obj.city3 #
# obj.city4 #
<input type="submit" value="提交">
</form>
</body>
</html>
以上是关于Form验证实例的主要内容,如果未能解决你的问题,请参考以下文章
vue elementui el-form rules动态验证的实例代码详解
您如何验证两个 asp:FileUpload 实例以使用 jquery 验证文件?