Luke Kavanagh
Luke Kavanagh

Reputation: 229

Only allowing authenticated users to access certain pages in django

I've been trying to make it so that only a user that is logged can access a page but I can't seem to get it to work.

This is my views.py

@login_required
def course(request):
    data = Students.objects.all()
    context = {'data', data}
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/')
    else:
        return render_to_response('login/course.html', context)

I have also tried to restrict access by doing

{% if user.is_authenticated %}
    <h1>Course Page!</h1>
{% else %}
    <a href="/">login</a>
{% endif %}

The first way I tried in the views.py file always let me see the page and the second way always only displays the login link. It's probably something small but I can't seem to work it out. Would anyone be able to point me in the right direction?

Upvotes: 1

Views: 3382

Answers (2)

C14L
C14L

Reputation: 12558

This should be enough. If a anonymous user can still access that view function, the user is maybe authenticated.

@login_required(login_url='/')
def course(request):
    data = Students.objects.all()
    return render(request, 'login/course.html', {'data': data})

Are you sure that you are not authenticated? Try deleting cookies for localhost and open the view again.

Upvotes: 1

Curtis Olson
Curtis Olson

Reputation: 967

In your view, try passing the user through the response with something like:

return render_to_response('login/course.html', {'context': context, 'user': request.user})

Upvotes: 0

Related Questions