diadia

興味があることをやってみる。自分のメモを残しておきます。

django ユーザ認証の条件分岐

ユーザ認証に関わる条件分岐について

今回ユーザ認証したユーザとAnonymousUserで表示するものやプログラムの論理構造を変えようと思った。当初書いていたコードは例えば以下のもので、それは期待した挙動を得られなかった。

 

元のコード
hoge.views.py...

from django.shortcut import render
from hoge.models import Diary
from django.views.generic import Views

class DiaryView(View):
    def get(self, request, *args, **kwargs):
        if request.user:
            object_list = Diary.objects.all()
        
        else:
            object_list = Diary.objects.filter(private=False)
        
        context = {}
        context["object_list"] = object_list
        return render(request, "diary/ondex.html", context)

ユーザ認証している場合にはすべての記事を表示することができるが、認証されていないものは公開しても良いものだけ表示される仕組みを構築したかった。このコードは文法的なエラーが出なかった。しかしAnonymousUserの場合(elseの場合)の表示ができなかった。期待通りの挙動を実現するためにはis_authenticatedを使えば良いとわかった。

 

改善されたコード
hoge.views.py...

from django.shortcut import render
from hoge.models import Diary
from django.views.generic import Views

class DiaryView(View):
    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated :       #ここを変更された
            object_list = Diary.objects.all()
        
        else:
            object_list = Diary.objects.filter(private=False)
        
        context = {}
        context["object_list"] = object_list
        return render(request, "diary/ondex.html", context)

 

ドキュメント

request.user: https://docs.djangoproject.com/ja/2.1/ref/request-response/#django.http.HttpRequest.user

From the AuthenticationMiddleware: An instance of AUTH_USER_MODEL representing the currently logged-in user. If the user isn't currently logged in, user will be set to an instance of AnonymousUser. You can tell them apart with is_authenticated, like so:
if request.user.is_authenticated:
    ... # Do something for logged-in users. 
else:
    ... # Do something for anonymous users.

request.userは直近でログインしている場合はログインしたuserが返され、ログインしてなければAnonymousUserが返されるようだ。