我試圖在我的web應用程序中設置登錄會話,但無法使其工作。我是django的新手,並閱讀會話的文檔,但沒有連接到我的網絡應用程序。我目前所需要的是檢查用戶是否已登錄,是否重定向到登錄頁面。django的登錄會話
繼承人我試圖合併登錄會話的代碼。
settings.py
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'logins',
'dashboards'
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
urls.py
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'logins.views.login', name='login'),
url(r'^accounts/auth/$', 'logins.views.auth_view', name='auth_view'),
url(r'^accounts/dashboard/$', 'dashboards.views.dashboard', name='dashboard'),
url(r'^accounts/logout/$', 'logins.views.logout', name='logout'),
url(r'^accounts/invalid/$', 'logins.views.invalid', name='invalid'),
views.py用於登錄
from django.shortcuts import render, render_to_response, RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib import auth
from django.core.context_processors import csrf
def login(request):
c = {}
c.update(csrf(request))
return render_to_response('login.html', c)
def auth_view(request):
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 HttpResponseRedirect('/accounts/dashboard')
else:
return HttpResponseRedirect('/accounts/invalid')
def logout(request):
auth.logout(request)
return render_to_response('logout.html')
def invalid(request):
return render_to_response('invalid.html')
views.py爲信息中心應用這就是被登錄到
from django.shortcuts import render, render_to_response, RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib import auth
from django.core.context_processors import csrf
def dashboard(request):
return render_to_response('dashboard.html')
您是否能避免特定的原因[內置的身份驗證系統(https://docs.djangoproject.com/en /1.6/topics/auth/default/#module-django.contrib.auth.views)?它具有重定向用戶的功能,如果他們沒有登錄到登錄頁面。 – rbonick 2014-09-03 20:05:45
@rbonick鏈接已死。 – 2016-05-21 16:11:34