django框架提供了登录和退出系统的login和logout的视图函数,本实现中使用系统自带的视图函数。需要settings.py,urls.py,views.py和模板文件等几个方面进行考虑。
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.locale.LocaleMiddleware'
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'website.wsgi.application'
import os.path
TEMPLATE_DIRS = (
'/liuzp/DataCrawl/djcode/website/templates',
'/liuzp/DataCrawl/djcode/website/css/bootstrap',
# 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.
)
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',
)
首先编写urls.py文件。如下所示,其中django.contrib.auth.views.login和django.contrib.auth.views.logout视图函数是django框架提供的。
from django.conf.urls import patterns, include, url
from website import views
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
from django.contrib.auth.views import login,logout
admin.autodiscover()
urlpatterns = patterns('',
#登陆
(r'^accounts/login/$',login),
#退出
(r'^accounts/logout/$',logout),
#主界面
(r'^main/$',views.main),
)
其次编写views.py文件。主要是编写/main/的视图函数。使用decorators.login_required的装饰件,用来控制非登录用户的访问页面的权限,并且登录成功后,可以回到需要访问的页面。
login_required()的用法是:首先如果用户没有登录,则重定向至settings.LOGIN_URL,并且在查询字符串中传递当前绝对路径;其次如果用户已经登录,那么就正常的执行视图函数。
#encoding=utf-8
from django.http import HttpResponse
from django.shortcuts import render_to_response
from dboperation.user import isuserexist
from users.models import User
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import login,logout
import datetime
@login_required(login_url='/accounts/login')
def main(request):
return render_to_response('main.html')
模板文件需要和login视图文件相对应,所以需要在template文件夹下建立/registration/login.html文件,作为登录界面。本文中的登录界面使用bootstrap的样式包。
如果账号和密码正确,则登录成功,页面将会重定向到next指定的URL中。如果next没有提供,则使用{{ next|add:"/main/" }}将页面重定向到/main/的界面。
NCTC数据抓取平台