Python – Retrieves SQL entries from Django logins

Retrieves SQL entries from Django logins… here is a solution to the problem.

Retrieves SQL entries from Django logins

I’m new to Django. I wrote a login script using the built-in User model.

def login_user(request):
    state = "Please login below..."
    username = password = ''
    if request. POST:
        username = request. POST['username']
        password = request. POST['password']

user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                state = "You're successfully logged in!"
                return render_to_response('home.html',{'username': username})
            else:
                state = "Your account is not active, please contact the site admin."
        else:
            state = "Your username and/or password were incorrect."

return render_to_response('index.html',{'state':state})

This opens a new page home, where I will display {{username}}.
But how about downloading from the database and displaying them on my home page. I’ve tried using User.objects.all() but it doesn’t seem to work.

Solution

You already have a user object, ( authenticate() returns it), so simply retrieve information from the user. Check out User documentation to see what you can get out of it:

# ...
user = authenticate(username=username, password=password)
if user is not None:
    if user.is_active:
        state = "You're successfully logged in!"
        info = dict(username=username, email=user.email, fullname=user.get_full_name())
        return render_to_response('home.html', info)

Related Problems and Solutions