Django框架封装外部函数示例

yipeiwu_com6年前Python基础

本文实例讲述了Django框架封装外部函数。分享给大家供大家参考,具体如下:

需求:我们来模拟用户登录,验证是否输入正确的用户名和密码

1.构建登录表单

  <form method="post">
    <p>用户名:<input type="text" name="username"></p>
    <p>密码:<input type="password" name="pwd"></p>
    <p><input type="submit" value="提交"></p>
    <hr>
  </form>
  <p>
    登录状态提示:{{ result }}
  </p>

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程序设计有所帮助。

相关文章

python实现本地图片转存并重命名的示例代码

//有1-22个文件夹,各文件夹下有Detect_0文件夹,此文件夹下有source与mask文件夹,目的是将需要获取图片的 文件夹下的图片复制到新的文件夹下并按顺序重命名 impo...

django小技巧之html模板中调用对象属性或对象的方法

django小技巧之html模板中调用对象属性或对象的方法

环境:依赖最初test2数据库            python3版本  ...

Numpy之random函数使用学习

random模块用于生成随机数,下面看看模块中一些常用函数的用法: numpy.random.rand(d0, d1, ..., dn):生成一个[0,1)之间的随机浮点数或N维浮点...

详解python中的模块及包导入

python中的导入关键字:import 以及from  import 1、import   import一般用于导入包以及模块。   不过有个小问题:   (1)当导入的是...

详解Python的Twisted框架中reactor事件管理器的用法

详解Python的Twisted框架中reactor事件管理器的用法

铺垫 在大量的实践中,似乎我们总是通过类似的方式来使用异步编程: 监听事件 事件发生执行对应的回调函数 回调完成(可能产生新的事件添加进监听队列) 回到1,监听事件...