我正在使用 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 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/