服务器之家

服务器之家 > 正文

Django框架封装外部函数示例

时间:2021-06-30 00:19     来源/作者:学习笔记666

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

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

1.构建登录表单

?
1
2
3
4
5
6
7
8
9
<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.程序判断

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#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框架的验证机制

Django框架封装外部函数示例

这是为了防止跨域攻击,我们这里暂时不研究这个安全机制,来到settings.py文件注释掉下面这行

Django框架封装外部函数示例

这样就不会报上面的那个错误了。

如果用户输正确的用户名和密码(jack、123),模板上{{ result }} 就是提示“登录成功”。

4.如何把userLogin函数写到外部?

在views.py文件同级下新建user.py文件

Django框架封装外部函数示例

然后在views.py里

先引入

?
1
import user

使用

?
1
user.userLogin()

完整的views.py代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
#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程序设计有所帮助。

原文链接:https://blog.csdn.net/github_26672553/article/details/52493519

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
2021德云社封箱演出完整版 2021年德云社封箱演出在线看
2021德云社封箱演出完整版 2021年德云社封箱演出在线看 2021-03-15
返回顶部