[Django]-Django.contrib.auth.logout in Django

14πŸ‘

βœ…

Look at the source of the logout method, it should give you a clear idea what’s going on. You can add extra arguments to the logout method to handle redirecting, but you can also append after the method for custom behaviour

def logout(request, next_page=None,
           template_name='registration/logged_out.html',
           redirect_field_name=REDIRECT_FIELD_NAME,
           current_app=None, extra_context=None):
    """
    Logs out the user and displays 'You are logged out' message.
    """
    auth_logout(request)
    redirect_to = request.REQUEST.get(redirect_field_name, '')
    if redirect_to:
        netloc = urlparse.urlparse(redirect_to)[1]
        # Security check -- don't allow redirection to a different host.
        if not (netloc and netloc != request.get_host()):
            return HttpResponseRedirect(redirect_to)
    #etc...

23πŸ‘

Django has a shortcut method called redirect. You could use that to redirect like this:

from django.contrib.auth import logout
from django.shortcuts import redirect

def logout_view(request):
    logout(request)
    return redirect('home')

Where home is the name of a url pattern you defined in urls.py like this:

urlpatterns = patterns('',
    url(r'^$', 'blah.views.index', name='home'))
)

In the redirect call you could use a path as well, like / to redirect to the site root, but using named views is much cleaner.

PS: the code posted by @Hedde is from django.contrib.auth.views module, logout method. If that’s what you want to use, you can import it like this:

from django.contrib.auth.views import logout
πŸ‘€janos

18πŸ‘

You don’t have to write a view for that, you can just do:

(r'^accounts/logout/$', 'django.contrib.auth.views.logout',{'next_page': '/accounts/login'})

More info: https://docs.djangoproject.com/en/dev/topics/auth/default/#django.contrib.auth.views.logout

πŸ‘€user2067956

1πŸ‘

def logout_user(request):
    # Log out the user.
    # since function cannot be same as django method, esle it will turn into recursive calls
    logout(request)
    # Return to homepage.
    return HttpResponseRedirect(reverse('registeration:index'))
πŸ‘€Urvashi Meena

1πŸ‘

urlpatterns =[
path('accounts/logout/', views.LogoutView.as_view(template_name="post_list.html"), name='logout'),
]

write a template_name as above inside it worked for me.Hope it might be useful.
Thankyou

πŸ‘€Nikhil Lingam

Leave a comment