python - 如何在 django 的 views.py 中获取登录用户名

标签 python html django authentication oauth

实际上我对 django 和 python 很陌生。在/templates/home.html 中,添加了 {{ user.username }} 它显示当前登录的用户名

<p>Welcome {{ user.username }} !!!</p>

我想在 views.py 文件中获取当前登录的用户名。如何获取用户名?

我尝试了不同的方法,但我没有得到结果

  1. user = User.objects.get(username=request.user.username)
  2. username = request.GET['username']
  3. def sample_view(请求): current_user = request.user 打印(当前用户)

请告诉我,如何实现我的结果。

我的 views.py 看起来像这样。我的 views.py 有什么问题吗

    #!python
    #log/views.py
    from django.shortcuts import render
    from django.contrib.auth.decorators import login_required
    from django.template import Context
    from contextlib import contextmanager
    # Create your views here.
    # this login required decorator is to not allow to any
    # view without authenticating
    @login_required(login_url="login/")
    def home(request):
         return render(request,"home.html")
#dummy_user = {{ username }}
#user = User.objects.get(username=request.user.username)
#username = request.GET['username']
#print(usernam
#user = request.user
#print(user)

    def sample_view(request):
            current_user = {}
            #current_user['loggeduser'] = request.user
             #or
            current_user['loggeduser'] = request.user.username
            return render(request,"home.html",current_user)
           # print(current_user.id)

最佳答案

前提是你启用了authentication middleware ,您无需执行任何操作。用户名出现在您的模板中这一事实表明您已启用它。每个 View 都可以访问 request.user,它是 User 模型的一个实例。所以以下是非常多余的

user = User.objects.get(username=request.user.username)

因为你已经有了request.user.username!!如果你想找到用户的电子邮件,你做 request.user.email 或者只是做

user = request.user 

并使用新创建的变量(例如user.username)

引用:https://docs.djangoproject.com/en/1.10/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:

关于python - 如何在 django 的 views.py 中获取登录用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39785934/

相关文章:

python - Django 管理员登录屏幕上出现错误

python - 直接引用 Python 的标准库

javascript - 使用 requestAnimationFrame 对 HTML 视频进行动画处理

python - django 两个外键到同一模型 - 管理错误

android - 在 Android 中的文本输入上提供笑脸按钮

html - BootStrap 在折叠时显示元素

python - Django Gunicorn worker 无法启动

python - 在瓶中使用 POST 方法时获取 405 方法不允许

python - 试图在数据集中找到最优价格点

python - 如何将列表拆分为大小相等的 block ?