国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

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="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>    <![endif]-->    <!--    <script src="http://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.survivalescaperooms.com/starof/p/4724381.html有問題歡迎與我討論,共同進步。

 


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 平陆县| 桦甸市| 阳曲县| 钟祥市| 桐城市| 济阳县| 玉环县| 通州区| 抚州市| 靖远县| 合肥市| 舟山市| 台州市| 石林| 屏东县| 江孜县| 六盘水市| 宕昌县| 万源市| 团风县| 荥阳市| 红桥区| 盐边县| 襄汾县| 平凉市| 大丰市| 田林县| 镇康县| 咸宁市| 湄潭县| 池州市| 固原市| 晋州市| 施甸县| 海南省| 博爱县| 连南| 嵊州市| 白玉县| 邯郸市| 淳安县|