day
day

Reputation: 1157

Django User Logout Fails to Redirect Homepage

After log out user in my django web app, the redirected homepage still displays the "Log Out" button instead of the "Sign in with Facebook". In the following code, I follow the django documentation to logout the user and redirect the page to homepage which is the base.html. It seems that my web app still has user.is_authenticated as True after log out? What am I missing?

I cannot find any useful hint online. Any comment is much appreciated.

Here is part of my template html

<div class="navbar-form navbar-right">
                    {% if user.is_authenticated %}
                      <a id="logout" href="/accounts/logout" class="btn btn-success">Logout</a>
                    {% else %} 
                      <a id="facebook_login" href="/accounts/facebook/login" class="btn btn-success">Sign in with Facebook</a>
                    {% endif %}
</div>

Here is my urls.py

url(r'^$', 'homepage.views.home', name='home'),
url(r'^accounts/', include('allauth.urls')),
url(r'^accounts/logout/$', 'homepage.views.logout', name='logout'),

Here is my homepage/views.py

# Create your views here.
def home(request):
    return render(request, "base.html", {})

# ensure only logged in users can access the view.
@login_required
def logout(request):
    logout(request)
    # Take the user back to the homepage.
    return redirect('home')

Upvotes: 1

Views: 486

Answers (1)

karthikr
karthikr

Reputation: 99660

There are 2 things here:

  1. You need to reorder the URLs

from:

url(r'^accounts/', include('allauth.urls')),
url(r'^accounts/logout/$', 'homepage.views.logout', name='logout'),

to

url(r'^accounts/logout/$', 'homepage.views.logout', name='logout'),
url(r'^accounts/', include('allauth.urls')),

This way, your logout takes precedence over the allauth's logout URL pattern

  1. You should be aliasing the imported logout, or rename your logout to something different.

Example:

from django.contrib.auth import logout as auth_logout

and then

def logout(request):
    auth_logout(request)

    ....

Upvotes: 1

Related Questions