0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[python] Djangoでログイン状況を確認

Posted at

はじめに

nodejs などではpassportを使ってミドルウェアでログイン確認をしていたが、Djangoではそれさえも簡単にできるということなので、少しながらまとめてみた。

環境

Django 3.1.13
python 3.9

Code

ログイン有無の確認

view.py
def show_aaa(request, aaa_id):
    aaa = AAA.objects.get(pk=aaa_id)

    if request.user.is_authenticated:
    # Login: True , not Login: False
        return render(request, 'show_aaa.html', {})
    else:
        return render(request, 'login.html', {})

ログイン状態ならTrue
ログイン状態でないならFalse

匿名ユーザーであることを確認

request.user.is_anonymous
# Login: False, not Login : True

匿名状態なら(ログイン状態でないはい)True
匿名状態でないなら(ログイン状態なら)False
Djangoのドキュメントによると、匿名による判断はあまり推奨しないそうです。is_authenticatedで判断ができてしまうので

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?