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

相关文章

wxPython中listbox用法实例详解

本文实例讲述了wxPython中listbox用法。分享给大家供大家参考。具体如下: # load a listbox with names, select a name and d...

Python pip替换为阿里源的方法步骤

Python pip替换为阿里源的方法步骤

背景 由于 python 自带的源下载速度非常慢,特别是安装一些库的时候,甚至有时会失败。 pip国内的一些镜像   阿里云 http://mirror...

Django中STATIC_ROOT和STATIC_URL及STATICFILES_DIRS浅析

前言 本文主要给大家介绍关于Django中STATIC_ROOT和STATIC_URL及STATICFILES_DIRS的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细...

python range()函数取反序遍历sequence的方法

python中的range函数取反序有两种方式 第一种:先构建一个列表,然后对列表中的元素进行反转。 例如: a=range(5) for i in reversed(a):...

python Django中的apps.py的目的是什么

This question has been asked earlier: 07000 Application configuration objects store metadata...