2011-02-04 4 views

答えて

1

、あなたのプロジェクトでそれを有効にしてください。私はあなたがしかし、セッションを管理するためにdjango.contrib.authを使用することをお勧めします。データベースのセッションを管理します。これは、クッキーにユーザ名を保存するだけでなく、より安全です。

+0

を使用してそれを行う方法の一例であり、d – user596500

+0

ほか[どのようなロドリゲが言った](http://stackoverflow.com/questions/4898408/how-to-set-a-login-cookie-in-django/4898612#4898612)、MIDDLEWARE_CLASSESのリストが必ずsettings.py 'django.middleware.common.CommonMiddleware'が含まれていますが、デフォルトになっていますので、何も触れていなければそこにあるはずです。マニュアルのlogin()メソッドと@login_requiredヘルパーを見てください。 –

2

django.contrib.authアプリ。サイトにログイン機能を追加する最善の方法です。このアプリ。 django.contrib.sessionsアプリとミドルウェアを使用します。

セッションミドルウェアは、ユーザーのブラウザにCookieを設定した後に表示されます。次に、あなたのコードでは、それはあなたがログインするユーザーを強制的に自分の意見を飾るために必要があることを意味します

from django.contrib.auth.decorators import login_required 

@login_required 
def my_view(request): 
    ... 

ビューの中で、あなたがしてある

  • request.sessionへのアクセスを持っていますあなたはuserオブジェクト

あるセッション

  • request.user、全体でデータを保存することができdict私はyと助言しますドキュメントを読むことができます。ドキュメントは、ここではDjango

  • 6

    の最良の部分の一つは、あなたがDjangoのブランチで新しい淫魔becuz、私のコードか何かを与えることができますミドルウェア

    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 
    
    関連する問題