首页 > 学院 > 开发设计 > 正文

django用户登录和注销

2019-11-14 17:05:03
字体:
来源:转载
供稿:网友

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]# lsaccounts  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]# lsaccounts  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 syncdbCreating tables ...Creating table auth_permissionCreating table auth_group_permissionsCreating table auth_groupCreating table auth_user_user_permissionsCreating table auth_user_groupsCreating table auth_userCreating table django_content_typeCreating table django_sessionCreating table django_siteYou just installed Django's auth system, which means you don't have any superusers defined.Would you like to create one now? (yes/no): yesUsername (leave blank to use 'root'): liuxiaoyanE-mail address: liuxiaoyan@test.comPassword: 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-8from django import formsfrom django.contrib.auth.models import Userfrom bootstrap_toolkit.widgets import BootstrapDateInput,BootstrapTextInput,BootstrapUneditableInputclass 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 authfrom django.contrib import messagesfrom django.template.context import RequestContext from django.forms.formsets import formset_factoryfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPagefrom bootstrap_toolkit.widgets import BootstrapUneditableInputfrom django.contrib.auth.decorators import login_requiredfrom forms import LoginFormdef 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_requireddef 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',安装即可。

 

资源链接

http://blog.csdn.net/dbanote/article/details/11465447

http://my.oschina.net/u/569730/blog/369144

 

 

本文作者starof,因知识本身在变化,作者也在不断学习成长,文章内容也不定时更新,为避免误导读者,方便追根溯源,请诸位转载注明出处:http://www.VEVb.com/starof/p/4724381.html有问题欢迎与我讨论,共同进步。

 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表