Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current user in view

I'm using django authentication to login the user:

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)

However, I can't seem to access the current user in any other view. In every template, I have access to the user, but I don't seem to access in the view itself. For example, in another route I want to be able to do the following:

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

But I keep on getting an error that user is a Nonetype object. Any ideas?

like image 789
Aloke Desai Avatar asked May 04 '14 00:05

Aloke Desai


1 Answers

You need to access user through the request that you get. You'll use request.user Change your view to:

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

Django documentation here and here.

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.

like image 85
Alex Avatar answered Oct 25 '22 04:10

Alex