django的登录会话 [英] login sessions for django

查看:97
本文介绍了django的登录会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Web应用程序中设置登录会话,但无法使其正常工作。我是django的新手,并阅读了会话文档,但未连接到我的网络应用程序。我目前只希望检查用户是否已登录,以及是否未重定向到登录页面。



这里是我尝试合并的代码登录会话。



settings.py

  INSTALLED_APPS =(
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'logins',
'dashboard'


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



<来自django.conf.urls的pre> 导入模式,包括来自django.conf的url
导入设置来自django.conf.urls.static的
导入静态
从django.contrib导入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 /仪表盘/$'、'dashboards.views.dashboard',名称='dashboard'),
url(r'^ accounts / logout / $','logins.views.logout',name ='logout') ,
url(r'^ accounts / invalid / $','logins.views.invalid',name ='invalid'),

views.py进行登录

 从django.shortcuts导入render,render_to_response,RequestContext来自django.http的
导入HttpResponseRedirect,来自django.contrib的HttpResponse
源自django.core.context_processors的auth
导入csrf

def login(request):
c = {}
c.update(csrf(request))
return render_to_response('login.html',c)

def auth_view(request):
用户名= request.POST.get('用户名','')
password = request.POST.get('password','')
user = auth.authenticate(用户名=用户名,密码=密码)

如果user不为None并且user.is_active:
auth.login(request,user)
返回HttpResponseRedirect('/ accounts / dashboard')
else:
return HttpResponseRedirect('/ accounts / invalid')

def logout(request):
auth.logout (请求)
返回render_to_response('logout.html')

def无效(请求):
返回render_to_response('invalid.html')

views.py用于已登录的仪表板应用

 django.shortcuts中的导入render,render_t o_response,来自django的RequestContext 
.http导入HttpResponseRedirect,来自django.Http的HttpResponse
.contrib从django.core.context_processors导入auth
导入csrf

def仪表盘:
return render_to_response('dashboard.html')


解决方案

在django中执行此操作非常简单:
在此示例中,会话将保存在数据库中(您必须将django应用程序与数据库同步)



用户登录:

 从django.contrib.auth.models导入用户
从django.contrib .auth导入身份验证,如果request.method =='POST',则登录

用户名= request.POST.get('昵称','')
密码= request.POST.get ('password','')
用户=身份验证(用户名=用户名,密码=密码)
如果user不是None:
if user.is_active:
request.session .set_expiry(86400)#设置exp。会话的值
login(请求,用户)#用户现在已登录

对于其他站点(需要登录的站点):

  def my_func(request):
(如果需要) .user.is_authenticated():
打印(user.id)#用户已登录

或者您使用 login_require -decorator:

 来自django.contrib .auth.decorators import login_required 

@login_required
def my_func(request):
print(user.id)#用户已登录


I'm trying to set login sessions within my web app but can not get it to work. I'm new to django and read the documentation for sessions but not making the connection to my web app. All I want from it at the moment is to check if a user is logged in and if not redirect to the login page.

Heres the code that i am trying to incorporate login sessions.

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 for logins

    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 for dashboard app thats being logged into

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

解决方案

Its very simple to do that in django: In this example the sessions will be saved in the db (you have to sync your django app with your database)

User-Login:

from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
if request.method == 'POST':
    username = request.POST.get('nickname','')
    password = request.POST.get('password','')
    user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                request.session.set_expiry(86400) #sets the exp. value of the session 
                login(request, user) #the user is now logged in

And for the other sites (where you need to be loggedin):

def my_func(request):
    if request.user.is_authenticated():
        print (user.id) #the user is loggedin

Or you use the login_require-decorator:

from django.contrib.auth.decorators import login_required

@login_required
def my_func(request):
    print(user.id) #the user is loggedin

这篇关于django的登录会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆