django用户登录和注销的实现方法
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+端口访问,出现登录界面
2、当用户名或密码为空时,提示“用户名和密码为必填项”
3、当用户名或密码错误时,提示“用户名或密码错误”
4、输入正确用户名和密码(创建数据库时生成的liuxiaoyan,password),进入主页
5、点击登出,注销登录,返回登录页面。
四、排错
1、'bootstrap_toolkit' is not a valid tag library
因为你的installed_app没有安装'bootstrap_toolkit',安装即可。
资源链接
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。