最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

django用戶登錄和注銷的實(shí)現(xiàn)方法

 更新時(shí)間:2018年07月16日 13:47:41   作者:https://www.cnblogs.com/starof/p/4724381.html  
這篇文章主要介紹了django用戶登錄和注銷的實(shí)現(xiàn)方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

django版本:1.4.21。

一、準(zhǔn)備工作

1、新建項(xiàng)目和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

在項(xiàng)目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

在項(xiàng)目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目錄來(lái)存放模板,

[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、配置數(shù)據(jù)庫(kù)

我用的是mysql數(shù)據(jù)庫(kù),先創(chuàng)建數(shù)據(jù)庫(kù)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.
 } 
}

然后同步數(shù)據(jù)庫(kù):同步過(guò)程創(chuàng)建了一個(gè)管理員賬號(hào):liuxiaoyan,password,后面就用這個(gè)賬號(hào)登錄和注銷登錄。

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

至此,準(zhǔn)備工作完成。

二、實(shí)現(xiàn)登錄功能

使用django自帶的用戶認(rèn)證,實(shí)現(xiàn)用戶登錄和注銷。

1、定義一個(gè)用戶登錄表單(forms.py)

因?yàn)橛玫牧薭ootstrap框架,執(zhí)行命令#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沒有強(qiáng)制規(guī)定,建議放在和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':'請(qǐng)輸入用戶名'},
   widget=forms.TextInput(
    attrs={
     'placeholder':u"用戶名",
     } 
    ) 
   ) 

 password = forms.CharField(
   required=True,
   label=u"密碼",
   error_messages={'required':u'請(qǐng)輸入密碼'},
   widget=forms.PasswordInput(
    attrs={
     'placeholder':u"密碼",
     } 
    ), 
   ) 

 def clean(self):
  if not self.is_valid():
   raise forms.ValidationError(u"用戶名和密碼為必填項(xiàng)")
  else:
   cleaned_data = super(LoginForm,self).clean()

定義的登錄表單有兩個(gè)域username和password,這兩個(gè)域都為必填項(xiàng)。

2、定義登錄視圖views.py

在視圖里實(shí)例化上一步定義的用戶登錄表單

# 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,}))

該視圖實(shí)例化了前面定義的LoginForm,它的主要業(yè)務(wù)流邏輯是:

1、判斷必填項(xiàng)用戶名和密碼是否為空,如果為空,提示“用戶名和密碼為必填項(xiàng)”的錯(cuò)誤信息。

2、判斷用戶名和密碼是否正確,如果錯(cuò)誤,提示“用戶名或密碼錯(cuò)誤”的錯(cuò)誤信息。

3、登錄成功后,進(jìn)入主頁(yè)(index.html)

3、登錄頁(yè)面模板(login.html)

<!DOCTYPE html>
{% load bootstrap_toolkit %}
{% load url from future %}
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>數(shù)據(jù)庫(kù)腳本發(fā)布系統(tǒng)</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>錯(cuò)誤!</h4>用戶名或密碼錯(cuò)誤
  </div>
 {% endif %} 
 <div class="well">
  <h1>數(shù)據(jù)庫(kù)腳本發(fā)布系統(tǒng)</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、首頁(yè)(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),
               )

登錄視圖如下:調(diào)用djagno自帶用戶認(rèn)證系統(tǒng)的logout,然后返回登錄界面。

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

上面@login_required標(biāo)示只有登錄用戶才能調(diào)用該視圖,否則自動(dòng)重定向到登錄頁(yè)面。

三、登錄注銷演示

1、執(zhí)行python manage.py runserver 0.0.0.0:8000

在瀏覽器輸入ip+端口訪問(wèn),出現(xiàn)登錄界面

2、當(dāng)用戶名或密碼為空時(shí),提示“用戶名和密碼為必填項(xiàng)”

3、當(dāng)用戶名或密碼錯(cuò)誤時(shí),提示“用戶名或密碼錯(cuò)誤”

4、輸入正確用戶名和密碼(創(chuàng)建數(shù)據(jù)庫(kù)時(shí)生成的liuxiaoyan,password),進(jìn)入主頁(yè)

5、點(diǎn)擊登出,注銷登錄,返回登錄頁(yè)面。

四、排錯(cuò)

1、'bootstrap_toolkit' is not a valid tag library

因?yàn)槟愕腎NSTALLED_APP沒有安裝'bootstrap_toolkit',安裝即可。

資源鏈接

http://m.fzitv.net/article/143857.htm

http://m.fzitv.net/article/143850.htm

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 利用Python實(shí)現(xiàn)數(shù)值積分的方法

    利用Python實(shí)現(xiàn)數(shù)值積分的方法

    這篇文章主要介紹了利用Python實(shí)現(xiàn)數(shù)值積分。本文主要用于對(duì)比使用Python來(lái)實(shí)現(xiàn)數(shù)學(xué)中積分的幾種計(jì)算方式,并和真值進(jìn)行對(duì)比,加深大家對(duì)積分運(yùn)算實(shí)現(xiàn)方式的理解
    2022-02-02
  • 使用python將excel數(shù)據(jù)導(dǎo)入數(shù)據(jù)庫(kù)過(guò)程詳解

    使用python將excel數(shù)據(jù)導(dǎo)入數(shù)據(jù)庫(kù)過(guò)程詳解

    這篇文章主要介紹了使用python將excel數(shù)據(jù)導(dǎo)入數(shù)據(jù)庫(kù)過(guò)程詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-08-08
  • numpy中np.append()函數(shù)用法小結(jié)

    numpy中np.append()函數(shù)用法小結(jié)

    在numpy的函數(shù)庫(kù)中,np.append()函數(shù)是一個(gè)常用的數(shù)組操作函數(shù),它在進(jìn)行數(shù)組操作時(shí)能夠?qū)蓚€(gè)數(shù)組進(jìn)行拼接,并返回一個(gè)拼接后的新數(shù)組,下面就來(lái)介紹一下具體用法,感興趣的可以了解一下
    2023-11-11
  • 在Python3中使用asyncio庫(kù)進(jìn)行快速數(shù)據(jù)抓取的教程

    在Python3中使用asyncio庫(kù)進(jìn)行快速數(shù)據(jù)抓取的教程

    這篇文章主要介紹了在Python3中使用asyncio進(jìn)行快速數(shù)據(jù)抓取,asyncio是一個(gè)異步IO庫(kù),運(yùn)行效率較高,需要的朋友可以參考下
    2015-04-04
  • 解決python訓(xùn)練模型報(bào)錯(cuò):BrokenPipeError:?[Errno?32]?Broken?pipe

    解決python訓(xùn)練模型報(bào)錯(cuò):BrokenPipeError:?[Errno?32]?Broken?pipe

    這篇文章主要介紹了解決python訓(xùn)練模型報(bào)錯(cuò):BrokenPipeError:?[Errno?32]?Broken?pipe問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-07-07
  • Python這樣操作能存儲(chǔ)100多萬(wàn)行的xlsx文件

    Python這樣操作能存儲(chǔ)100多萬(wàn)行的xlsx文件

    這篇文章主要介紹了Python這樣操作能存儲(chǔ)100多萬(wàn)行的xlsx文件的方法,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-04-04
  • 用Python寫一個(gè)球球大作戰(zhàn)小游戲

    用Python寫一個(gè)球球大作戰(zhàn)小游戲

    這篇文章主要介紹了如何用Python寫一個(gè)球球大作戰(zhàn)小游戲,我們需要實(shí)現(xiàn)每位玩家操控一個(gè)可自由移動(dòng)的小球球,通過(guò)滑動(dòng)屏幕,你可以指揮自己的球球在地圖上四處游走,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-08-08
  • 對(duì)Python實(shí)現(xiàn)累加函數(shù)的方法詳解

    對(duì)Python實(shí)現(xiàn)累加函數(shù)的方法詳解

    今天小編就為大家分享一篇對(duì)Python實(shí)現(xiàn)累加函數(shù)的方法詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-01-01
  • 使用Python清空特定路徑下所有文件夾下中的文件

    使用Python清空特定路徑下所有文件夾下中的文件

    這篇文章主要為大家詳細(xì)介紹了如何使用python清空特定路徑下所有文件夾下中的文件并把空文件夾要保留下來(lái),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2025-01-01
  • 如何解決PyCharm顯示:無(wú)效的Python?SDK

    如何解決PyCharm顯示:無(wú)效的Python?SDK

    這篇文章主要介紹了在不同電腦之間傳輸Python項(xiàng)目時(shí)遇到的路徑問(wèn)題,并提供了解決方法,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下
    2025-01-01

最新評(píng)論

房产| 平罗县| 都安| 都匀市| 齐齐哈尔市| 新闻| 南华县| 卓资县| 特克斯县| 临颍县| 肇东市| 兰坪| 沽源县| 莒南县| 遂平县| 栖霞市| 铜山县| 平南县| 鸡泽县| 江都市| 左贡县| 阿荣旗| 兰溪市| 绵阳市| 滦平县| 石林| 娱乐| 应用必备| 博爱县| 四子王旗| 深泽县| 科技| 扶风县| 凤山市| 宣威市| 正镶白旗| 安平县| 崇文区| 巴青县| 盐津县| 安远县|