Search code examples
pythondjangodjango-usersdjango-login

Django Login, template doesn't recognize logged user


I'm writing an app that handles user autentificacion, and now I'm trying to do that feature.

My urlpatterns is this:

login page template, calls a html with a form that makes a POST to get username and password

url(r'^$', views.login_page, name='login_page'),

called from login form, recieves POST data (username, password) authenticate a user, does login and redirects to index page

url(r'^auth', views.auth_user, name='auth'),

index page, here we have to be logged to see it's content

url(r'^index$', views.index, name='index'),

So it seems to work, I go to 127.0.0.1:8000/AcademyApp/ to start, it shows login form, login form send data to auth view, makes auth, login and redirects to index, but index its like it can't read logged user data, I'm trying to do:

<h1>HI {{user.username}} !!</h1>

and it shows nothing, just blank.

I readed in django tutorial but I think it's not so much complete this feature, or I don't understand it at all :(

Here I put some important pieces of code:

ACADEMYAPP/URLS.PY

urlpatterns = [

    url(r'^$', views.login_page, name='login_page'),
    url(r'^auth', views.auth_user, name='auth'),
    url(r'^index$', views.index, name='index'),

HTML_LOGIN_FORM

<form action="/AcademyApp/auth" method="post">
    username: 
    <input type="text" name="username" value="" /><br />
    password:
    <input type="password" name="password" value="" /><br />
    <input type="submit" value="Log In" />
</form>

VIEWS.PY

def login_page(request):
    template = loader.get_template('AcademyApp/login.html')
    return HttpResponse(template.render())


def auth_user(request):
    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)
            # Redirect to a success page.
            return redirect("index")

        else:
            # Return a 'disabled account' error message
            template = loader.get_template('AcademyApp/error.html')
    else:
        # Return an 'invalid login' error message.
        template = loader.get_template('AcademyApp/error.html')

    return HttpResponse(template.render())


@login_required
def index(request, user):
    template = loader.get_template('AcademyApp/index.html')
    return HttpResponse(template.render())

Thanks for your help mates


Solution

  • In order for the template to gain access to the user variable, you need to render it with a RequestContext. But you're not passing any context at all. Instead of calling the template loader and render methods directly, you should use the render shortcut.

    def index(request, user):
        return render(request, 'AcademyApp/index.html', {})