How can I get the username of the logged-in user in Django?

前端 未结 6 1616
后悔当初
后悔当初 2020-12-13 03:45

How can I get information about the logged-in user in a Django application?

For example:

I need to know the username of the logged-in user to say who posted

6条回答
  •  情书的邮戳
    2020-12-13 04:06

    You can use the request object to find the logged in user

    def my_view(request):
        username = None
        if request.user.is_authenticated():
            username = request.user.username
    

    According to https://docs.djangoproject.com/en/2.0/releases/1.10/

    In version Django 2.0 the syntax has changed to

    request.user.is_authenticated
    

提交回复
热议问题