2011-02-04 121 views

回答

1

您可以通过使用session middleware实现这一点,请确保启用它在你的项目中。尽管如此,我建议您使用django.contrib.auth来管理会话。它管理数据库中的会话,比仅仅将用户名保存在cookie中安全得多

+0

你能不能给我一个代码什么的,becuz伊马在Django分支新的实例; d – user596500 2011-02-04 13:27:15

2

django.contrib.auth应用程序。是为您的网站添加登录功能的最佳方式。这个程序。使用django.contrib.sessions应用和中间件。

会话中间件会照顾你在用户浏览器中设置一个cookie。然后,在你的代码,这意味着你将需要来装饰你的意见,强制用户登录:

from django.contrib.auth.decorators import login_required 

@login_required 
def my_view(request): 
    ... 

内,您的观点,那么你将有机会获得

  • request.session,这是一个dict在那里你可以在会话
  • request.user,这是user对象

存储数据,我劝ÿ ou阅读文档。文档是Django的

的最好的地区之一
6

下面是如何使用中间件做

class UserCookieMiddleWare(object): 
    """ 
    Middleware to set user cookie 
    If user is authenticated and there is no cookie, set the cookie, 
    If the user is not authenticated and the cookie remains, delete it 
    """ 

    def process_response(self, request, response): 
     #if user and no cookie, set cookie 
     if request.user.is_authenticated() and not request.COOKIES.get('user'): 
      response.set_cookie("user", 'Hello Cookie') 
     elif not request.user.is_authenticated() and request.COOKIES.get('user'): 
      #else if if no user and cookie remove user cookie, logout 
      response.delete_cookie("user") 
     return response