2012-09-27 16 views
61

現在ログインしているユーザーのIDを取得するにはどうすればよいですか? models.py現在ログインしているユーザーのユーザーIDをDjangoで取得するには?

class Game(models.model): 
    name = models.CharField(max_length=255) 
    owner = models.ForeignKey(User, related_name='game_user', verbose_name='Owner') 

views.py中:

gta = Game.objects.create(name="gta", owner=?) 
+0

可能な重複[ジャンゴでは、私が知っているどのように現在ログインしているユーザ?](http://stackoverflow.com/questions/1477319/in-django-how-do-i-know-現在ログインしている私たち) –

答えて

108

まず、あなたのMIDDLEWARE_CLASSES設定に追加SessionMiddlewareAuthenticationMiddlewareミドルウェアを持っていることを確認してください。あなたは現在ログインしているユーザ表すUserオブジェクトを与える

def sample_view(request): 
    current_user = request.user 
    print current_user.id 

request.user

現在userは、あなたがでそれを得ることができ、requestオブジェクトです。ユーザーが現在ログインしていない場合、request.userAnonymousUserのインスタンスに設定されます。あなたはそうのように、is_authenticated()でそれらを区別することができます

if request.user.is_authenticated(): 
    # Do something for authenticated users. 
else: 
    # Do something for anonymous users. 
+0

リファレンス:https://docs.djangoproject.com/en/1.7/topics/auth/default/#authentication-in-web-requests – aliteralmind

+1

外部キーのユーザーIDをモデルに設定するとどうなりますか?現在ログインしているユーザーのIDですか? –

+0

設定を更新する必要はなくなりました。 https://docs.djangoproject.com/en/1.11/topics/auth/default/#authentication-in-web-requests –

5

はあなたのビューでは、DjangoのAuth Userを参照していると仮定:

def game(request): 
    user = request.user 

    gta = Game.objects.create(name="gta", owner=user) 
8

あなたは以下のコードを使用してユーザーに現在のログに記録されたにアクセスすることができます。

request.user.id 
関連する問題