python - 获取当前用户 View

标签 python django django-views django-authentication

我正在使用 django 身份验证来登录用户:

def signin(request):
        if request.method == "POST":
                username = request.POST.get("username").lower()
                password = request.POST.get("password").lower()
                user = authenticate(username = username, password=password)

但是,我似乎无法在任何其他 View 中访问当前用户。在每个模板中,我都可以访问用户,但我似乎无法访问 View 本身。例如,在另一条 route ,我希望能够执行以下操作:

def profile(request):
        skills = hasSkill.objects.filter(user__username=user.username)
        return render(request, "/profile.html", {"skills" : skills})

但我不断收到错误消息,提示用户是一个 Nonetype 对象。有什么想法吗?

最佳答案

你需要通过你得到的request来访问user。您将使用 request.user 将您的 View 更改为:

def profile(request):
        skills = hasSkill.objects.filter(user__username=request.user)
        return render(request, "/profile.html", {"skills" : skills})

Django 文档 herehere .

Django uses sessions and middleware to hook the authentication system into request objects.

These provide a request.user attribute on every request which represents the current user. If the current user has not logged in, this attribute will be set to an instance of AnonymousUser, otherwise it will be an instance of User.

关于python - 获取当前用户 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23451194/

相关文章:

python - 如何将本地文件分配给 Django 中的 FileField?

python - 在 Django 中发布数据值错误

django - 将 Bootstrap 和自定义 css 应用于 django 中的 {{form}} 元素

python - Django 如何根据选择字段验证请求的 URL?

python - 如何将 Django 变量作为 javascript 方法参数传递?

python - 在 Pandas 中将列拆分为两个新列

python - 在 ubuntu 14.04 中安装 Caffe

python - 如何在QGIS右上角设置DockWidget?

python - 在 django REST 框架中序列化一对多关系

python - jupyter 和 jupyter-notebook 有什么区别