mardi 28 juin 2016

request.user.is_authenticated returning false even though logged in


In the HTML template, request.user.is_authenticated keeps returning nothing, and it keeps acting like I have never logged in. I have logged in...

This is Home Views.py, after it logged in, it returns to home.html

@login_required
def home(request):
    print("USER?: " + str(request.user))
    print(request.user.is_authenticated)
    if not request.user.is_authenticated():
        return render_to_response('index.html')
    return render_to_response('home.html', request)

This is Account Views.py

def log_in(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            user = form.cleaned_data['username']
            pword = form.cleaned_data['password']
            user = authenticate(username = user, password = pword)
            if user is not None:
                # return render(, 'home.html')
                login(request, user)
                return HttpResponseRedirect('/home/')
            else:
                return render(request, 'login.html', { 'logform': form, 'error': True})
    else:
        if request.user.is_authenticated():
            return HttpResponseRedirect('/home/')
        else:
            form = LoginForm()
    return render(request, 'login.html', { 'logform':form,})

This is home.html document:

    {{ user.username }}
    {% if user.is_authenticated %}
        <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
    {% else %}
        <p>Welcome, new user. Please log in.</p>
    {% endif %}

{{ user.username }} does not show anything if I put it out the if/else statement. However, in login function, I print out the user.is_authenticated it shows my username printed and logged in. Also, in HTML document, it goes to else if I logged in or not logged in.

Any help would be great!


Aucun commentaire:

Enregistrer un commentaire