django用户登录和注销的实现方法


Posted in Python onJuly 16, 2018

django版本:1.4.21。

一、准备工作

1、新建项目和app

[root@yl-web-test srv]# django-admin.py startproject lxysite
[root@yl-web-test srv]# cd lxysite/
[root@yl-web-test lxysite]# python manage.py startapp accounts
[root@yl-web-test lxysite]# ls
accounts lxysite manage.py

2、配置app

在项目settings.py中的

INSTALLED_APPS = ( 
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 # Uncomment the next line to enable the admin:
 # 'django.contrib.admin',
 # Uncomment the next line to enable admin documentation:
 # 'django.contrib.admindocs',
 'accounts',
)

3、配置url

在项目urls.py中配置

urlpatterns = patterns('',
 # Examples:
 # url(r'^$', 'lxysite.views.home', name='home'),
 # url(r'^lxysite/', include('lxysite.foo.urls')),

 # Uncomment the admin/doc line below to enable admin documentation:
 # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

 # Uncomment the next line to enable the admin:
 # url(r'^admin/', include(admin.site.urls)),
 url(r'^accounts/', include('accounts.urls')),
)

4、配置templates

新建templates目录来存放模板,

[root@yl-web-test lxysite]# mkdir templates
[root@yl-web-test lxysite]# ls
accounts lxysite manage.py templates

然后在settings中配置

TEMPLATE_DIRS = ( 
 # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
 # Always use forward slashes, even on Windows.
 # Don't forget to use absolute paths, not relative paths.
 '/srv/lxysite/templates',
)

5、配置数据库

我用的是mysql数据库,先创建数据库lxysite

mysql> create database lxysite;
Query OK, 1 row affected (0.00 sec)

然后在settings.py中配置

DATABASES = { 
 'default': {
  'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
  'NAME': 'lxysite',      # Or path to database file if using sqlite3.
  'USER': 'root',      # Not used with sqlite3.
  'PASSWORD': 'password',     # Not used with sqlite3.
  'HOST': '10.1.101.35',      # Set to empty string for localhost. Not used with sqlite3.
  'PORT': '3306',      # Set to empty string for default. Not used with sqlite3.
 } 
}

然后同步数据库:同步过程创建了一个管理员账号:liuxiaoyan,password,后面就用这个账号登录和注销登录。

[root@yl-web-test lxysite]# python manage.py syncdb
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table django_site

You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (leave blank to use 'root'): liuxiaoyan
E-mail address: liuxiaoyan@test.com
Password: 
Password (again): 
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

至此,准备工作完成。

二、实现登录功能

使用django自带的用户认证,实现用户登录和注销。

1、定义一个用户登录表单(forms.py)

因为用的了bootstrap框架,执行命令#pip install django-bootstrap-toolkit安装。

并在settings.py文件中配置

INSTALLED_APPS = ( 
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 # Uncomment the next line to enable the admin:
 # 'django.contrib.admin',
 # Uncomment the next line to enable admin documentation:
 # 'django.contrib.admindocs',
 'bootstrap_toolkit',
 'accounts',
)

forms.py没有强制规定,建议放在和app的views.py同一目录。

#coding=utf-8
from django import forms
from django.contrib.auth.models import User
from bootstrap_toolkit.widgets import BootstrapDateInput,BootstrapTextInput,BootstrapUneditableInput

class LoginForm(forms.Form):
 username = forms.CharField(
   required = True,
   label=u"用户名",
   error_messages={'required':'请输入用户名'},
   widget=forms.TextInput(
    attrs={
     'placeholder':u"用户名",
     } 
    ) 
   ) 

 password = forms.CharField(
   required=True,
   label=u"密码",
   error_messages={'required':u'请输入密码'},
   widget=forms.PasswordInput(
    attrs={
     'placeholder':u"密码",
     } 
    ), 
   ) 

 def clean(self):
  if not self.is_valid():
   raise forms.ValidationError(u"用户名和密码为必填项")
  else:
   cleaned_data = super(LoginForm,self).clean()

定义的登录表单有两个域username和password,这两个域都为必填项。

2、定义登录视图views.py

在视图里实例化上一步定义的用户登录表单

# Create your views here.

from django.shortcuts import render_to_response,render,get_object_or_404 
from django.http import HttpResponse, HttpResponseRedirect 
from django.contrib.auth.models import User 
from django.contrib import auth
from django.contrib import messages
from django.template.context import RequestContext 

from django.forms.formsets import formset_factory
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage

from bootstrap_toolkit.widgets import BootstrapUneditableInput
from django.contrib.auth.decorators import login_required

from forms import LoginForm

def login(request):
 if request.method == 'GET':
  form = LoginForm()
  return render_to_response('login.html',RequestContext(request,{'form':form,}))
 else:
  form = LoginForm(request.POST)
  if form.is_valid():
   username = request.POST.get('username','')
   password = request.POST.get('password','')
   user = auth.authenticate(username=username,password=password)
   if user is not None and user.is_active:
    auth.login(request,user)
    return render_to_response('index.html',RequestContext(request))
   else:
    return render_to_response('login.html',RequestContext(request,{'form':form,'password_is_wrong':True}))
  else:
   return render_to_response('login.html',RequestContext(request,{'form':form,}))

该视图实例化了前面定义的LoginForm,它的主要业务流逻辑是:

1、判断必填项用户名和密码是否为空,如果为空,提示“用户名和密码为必填项”的错误信息。

2、判断用户名和密码是否正确,如果错误,提示“用户名或密码错误”的错误信息。

3、登录成功后,进入主页(index.html)

3、登录页面模板(login.html)

<!DOCTYPE html>
{% load bootstrap_toolkit %}
{% load url from future %}
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>数据库脚本发布系统</title>
 <meta name="description" content="">
 <meta name="author" content="朱显杰">
 {% bootstrap_stylesheet_tag %}
 {% bootstrap_stylesheet_tag "responsive" %}
 <style type="text/css">
  body {
   padding-top: 60px;
  } 
 </style>
 <!--[if lt IE 9]>
 <script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
 <![endif]-->
 <!-- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>-->
 {% bootstrap_javascript_tag %}
 {% block extra_head %}{% endblock %}
</head>

<body>

 {% if password_is_wrong %}
  <div class="alert alert-error">
   <button type="button" class="close" data-dismiss="alert">×</button>
   <h4>错误!</h4>用户名或密码错误
  </div>
 {% endif %} 
 <div class="well">
  <h1>数据库脚本发布系统</h1>
  <p>?</p>
  <form class="form-horizontal" action="" method="post">
   {% csrf_token %}
   {{ form|as_bootstrap:"horizontal" }}
   <p class="form-actions">
    <input type="submit" value="登录" class="btn btn-primary">
    <a href="/contactme/"><input type="button" value="忘记密码" class="btn btn-danger"></a>
    <a href="/contactme/"><input type="button" value="新员工?" class="btn btn-success"></a>
   </p>
  </form>
 </div>

</body>
</html>

配置accounts的urls.py

from django.conf.urls import *
from accounts.views import login,logout

 
urlpatterns = patterns('',
         url(r'login/$',login),
               )

4、首页(index.html)

代码如下:

<!DOCTYPE html>
{% load bootstrap_toolkit %}

<html lang="en">
{% bootstrap_stylesheet_tag %}
{% bootstrap_stylesheet_tag "responsive" %}

<h1>登录成功</h1>
<a href="/accounts/logout/"><input type="button" value="登出" class="btn btn-success"></a>

</html>

配置登出的url

from django.conf.urls import *
from accounts.views import login,logout

 
urlpatterns = patterns('',
         url(r'login/$',login),
         url(r'logout/$',logout),
               )

登录视图如下:调用djagno自带用户认证系统的logout,然后返回登录界面。

@login_required
def logout(request):
 auth.logout(request)
 return HttpResponseRedirect("/accounts/login/")

上面@login_required标示只有登录用户才能调用该视图,否则自动重定向到登录页面。

三、登录注销演示

1、执行python manage.py runserver 0.0.0.0:8000

在浏览器输入ip+端口访问,出现登录界面

django用户登录和注销的实现方法

2、当用户名或密码为空时,提示“用户名和密码为必填项”

django用户登录和注销的实现方法

3、当用户名或密码错误时,提示“用户名或密码错误”

django用户登录和注销的实现方法

4、输入正确用户名和密码(创建数据库时生成的liuxiaoyan,password),进入主页

django用户登录和注销的实现方法

5、点击登出,注销登录,返回登录页面。

四、排错

1、'bootstrap_toolkit' is not a valid tag library

因为你的INSTALLED_APP没有安装'bootstrap_toolkit',安装即可。

资源链接

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python 动态获取当前运行的类名和函数名的方法
Apr 15 Python
python执行外部程序的常用方法小结
Mar 21 Python
Python中asyncore异步模块的用法及实现httpclient的实例
Jun 28 Python
Python 判断是否为质数或素数的实例
Oct 30 Python
python自动化测试之如何解析excel文件
Jun 27 Python
Python3实现二叉树的最大深度
Sep 30 Python
Python基于WordCloud制作词云图
Nov 29 Python
Python IDE环境之 新版Pycharm安装详细教程
Mar 05 Python
解决paramiko执行命令超时的问题
Apr 16 Python
python开根号实例讲解
Aug 30 Python
基于python的opencv图像处理实现对斑马线的检测示例
Nov 29 Python
Python深度学习之Pytorch初步使用
May 20 Python
Flask框架实现给视图函数增加装饰器操作示例
Jul 16 #Python
flask框架使用orm连接数据库的方法示例
Jul 16 #Python
flask框架实现连接sqlite3数据库的方法分析
Jul 16 #Python
Sanic框架异常处理与中间件操作实例分析
Jul 16 #Python
对pycharm代码整体左移和右移缩进快捷键的介绍
Jul 16 #Python
对Python3.6 IDLE常用快捷键介绍
Jul 16 #Python
Sanic框架请求与响应实例分析
Jul 16 #Python
You might like
ThinkPHP写第一个模块应用
2012/02/20 PHP
PHP获取当前日期所在星期(月份)的开始日期与结束日期(实现代码)
2013/06/18 PHP
PHP  Yii清理缓存的实现方法
2016/11/10 PHP
用PHP将Unicode 转化为UTF-8的实现方法(推荐)
2017/02/08 PHP
php str_getcsv把字符串解析为数组的实现方法
2017/04/05 PHP
PHP7下协程的实现方法详解
2017/12/17 PHP
12个非常有创意的JavaScript小游戏
2010/03/18 Javascript
Jquery下:nth-child(an+b)的使用注意
2011/05/28 Javascript
使用JavaScript实现旋转的彩圈特效
2015/06/23 Javascript
JQuery 两种方法解决刚创建的元素遍历不到的问题
2016/04/13 Javascript
JS中script标签defer和async属性的区别详解
2016/08/12 Javascript
炫酷的js手风琴效果
2016/10/13 Javascript
BootStrap 图标icon符号图标glyphicons不正常显示的快速解决办法
2016/12/08 Javascript
修改ligerui 默认确认按钮的方法
2016/12/27 Javascript
理解javascript中的Function.prototype.bind的方法
2017/02/03 Javascript
深入浅出webpack教程系列_安装与基本打包用法和命令参数详解
2017/09/10 Javascript
webpack多页面开发实践
2017/12/18 Javascript
React router动态加载组件之适配器模式的应用详解
2018/09/12 Javascript
angular学习之动态创建表单的方法
2018/12/07 Javascript
Vue.js构建你的第一个包并在NPM上发布的方法步骤
2019/05/01 Javascript
使用vue打包进行云服务器上传的问题
2020/03/02 Javascript
django接入新浪微博OAuth的方法
2015/06/29 Python
python一键升级所有pip package的方法
2017/01/16 Python
python 第三方库的安装及pip的使用详解
2017/05/11 Python
Python用61行代码实现图片像素化的示例代码
2018/12/10 Python
Python3.5常见内置方法参数用法实例详解
2019/04/29 Python
Python发展史及网络爬虫
2019/06/19 Python
草莓网英国官网:Strawberrynet UK
2017/02/12 全球购物
国际花店:Pickup Flowers
2020/04/10 全球购物
linux比较文件内容的命令是什么
2013/03/04 面试题
艺术应用与设计个人的自我评价
2013/11/23 职场文书
培训心得体会
2013/12/29 职场文书
新领导上任欢迎词
2014/01/13 职场文书
师德师风事迹材料
2014/12/20 职场文书
2015年幼儿园班主任工作总结
2015/05/12 职场文书
python tqdm用法及实例详解
2021/06/16 Python