Python语言技术文档

微信小程序技术文档

php语言技术文档

jsp语言技术文档

asp语言技术文档

C#/.NET语言技术文档

html5/css技术文档

javascript

点击排行

您现在的位置:首页 > 技术文档 > Python网站web

Django框架封装外部函数示例

来源:中文源码网    浏览:196 次    日期:2024-05-01 06:39:21
【下载文档:  Django框架封装外部函数示例.txt 】


Django框架封装外部函数示例
本文实例讲述了Django框架封装外部函数。分享给大家供大家参考,具体如下:
需求:我们来模拟用户登录,验证是否输入正确的用户名和密码
1.构建登录表单

用户名:


密码:







登录状态提示:{{ result }}


2.程序判断
#coding:utf-8
from django.shortcuts import render,render_to_response
# Create your views here.
from django.http import HttpResponse
def hi(request):
msg = {'result':''}
if userLogin(request.POST.get('username'),request.POST.get('pwd')):
msg['result'] = '登录成功'
else:
msg['result'] = '登录失败'
return render_to_response("index.html",msg)
#判断用户登录函数
def userLogin(username,pwd):
if username == 'jack' and pwd == '123':
return True
else:
return False
验证如果输入的用户名为jack,密码为123,就提示“登录成功”
3.一个小意外
如果你提交上面的表单,会报如下错误,这个是Django框架的验证机制
这是为了防止跨域攻击,我们这里暂时不研究这个安全机制,来到settings.py文件注释掉下面这行
这样就不会报上面的那个错误了。
如果用户输正确的用户名和密码(jack、123),模板上{{ result }} 就是提示“登录成功”。
4.如何把userLogin函数写到外部?
在views.py文件同级下新建user.py文件
然后在views.py里
先引入
import user
使用
user.userLogin()
完整的views.py代码如下:
#coding:utf-8
from django.shortcuts import render,render_to_response
# Create your views here.
from django.http import HttpResponse
import user
def hi(request):
msg = {'result':''}
if user.userLogin(request.POST.get('username'),request.POST.get('pwd')):
msg['result'] = '登录成功'
else:
msg['result'] = '登录失败'
return render_to_response("index.html",msg)
希望本文所述对大家基于Django框架的Python程序设计有所帮助。

相关内容