温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用Django框架怎么封装外部函数

发布时间:2021-05-11 18:53:50 来源:亿速云 阅读:209 作者:Leah 栏目:开发技术

本篇文章为大家展示了使用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框架的验证机制

使用Django框架怎么封装外部函数

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

使用Django框架怎么封装外部函数

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

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

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

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

使用Django框架怎么封装外部函数

然后在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框架怎么封装外部函数,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI