django用戶登陸和註銷

django版本:1.4.21。javascript

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

二、配置app

在項目settings.py中的css

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',
)

三、配置url

在項目urls.py中配置html

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')),
)

四、配置templates

新建templates目錄來存放模板,html5

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

而後在settings中配置java

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',
)

五、配置數據庫

我用的是mysql數據庫,先建立數據庫lxysitepython

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

而後在settings.py中配置mysql

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,後面就用這個帳號登陸和註銷登陸。jquery

[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)

至此,準備工做完成。web

2、實現登陸功能

使用django自帶的用戶認證,實現用戶登陸和註銷。ajax

一、定義一個用戶登陸表單(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,這兩個域都爲必填項。

二、定義登陸視圖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,它的主要業務流邏輯是:

一、判斷必填項用戶名和密碼是否爲空,若是爲空,提示「用戶名和密碼爲必填項」的錯誤信息。

二、判斷用戶名和密碼是否正確,若是錯誤,提示「用戶名或密碼錯誤」的錯誤信息。

三、登陸成功後,進入主頁(index.html)

三、登陸頁面模板(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),
                                                         )   

四、首頁(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標示只有登陸用戶才能調用該視圖,不然自動重定向到登陸頁面。

 3、登陸註銷演示

一、執行python manage.py runserver 0.0.0.0:8000

在瀏覽器輸入ip+端口訪問,出現登陸界面

二、當用戶名或密碼爲空時,提示「用戶名和密碼爲必填項」

三、當用戶名或密碼錯誤時,提示「用戶名或密碼錯誤」

四、輸入正確用戶名和密碼(建立數據庫時生成的liuxiaoyan,password),進入主頁

五、點擊登出,註銷登陸,返回登陸頁面。

4、排錯

一、'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.cnblogs.com/starof/p/4724381.html有問題歡迎與我討論,共同進步。

相關文章
相關標籤/搜索