Django logout not working

I generally just use the contributed view to logout users. Simply add this to your root urls.py file:

# Would be nice to use settings.LOGIN_URL for `next_page` here, too
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/login'}),

and you'll be good to go.

Happy Djangoing.


Finally I totally switched to almost back to django defaults... Using:

in views.py:

from django.contrib.auth.forms import AuthenticationForm
from django.views.generic.edit import FormView

class LoginView(FormView):
    """
    This is a class based version of django.contrib.auth.views.login.


    """
    form_class = AuthenticationForm
    redirect_field_name = REDIRECT_FIELD_NAME
    template_name = 'iamapps/login.html'


    @method_decorator(csrf_protect)
    @method_decorator(never_cache)
    def dispatch(self, *args, **kwargs):
        return super(LoginView, self).dispatch(*args, **kwargs)

    def form_valid(self, form):
        """
        The user has provided valid credentials (this was checked in AuthenticationForm.is_valid()). So now we
        can check the test cookie stuff and log him in.
        """
        self.check_and_delete_test_cookie()
        login(self.request, form.get_user())
        return super(LoginView, self).form_valid(form)

    def get_context_data(self, **kwargs):
        context = super(LoginView, self).get_context_data(**kwargs)
        apps_settings=iamapps_settings()
        if apps_settings[LOGON_BASE_APP_NAME]:
            self.extend_template="%s/base.html" % apps_settings[LOGON_BASE_APP_NAME]
        else:
            self.extend_template="iamapps/base.html"
        context['extend_template']=self.extend_template
        return context    

    def form_invalid(self, form):
        """
        The user has provided invalid credentials (this was checked in AuthenticationForm.is_valid()). So now we
        set the test cookie again and re-render the form with errors.
        """
        self.set_test_cookie()
        return super(LoginView, self).form_invalid(form)

    def get_success_url(self):
        if self.success_url:
            redirect_to = self.success_url
        else:
            redirect_to = self.request.REQUEST.get(self.redirect_field_name, '')

        netloc = urlparse.urlparse(redirect_to)[1]
        if not redirect_to:
            redirect_to = settings.LOGIN_REDIRECT_URL
        # Security check -- don't allow redirection to a different host.
        elif netloc and netloc != self.request.get_host():
            redirect_to = settings.LOGIN_REDIRECT_URL
        return redirect_to

    def set_test_cookie(self):
        self.request.session.set_test_cookie()

    def check_and_delete_test_cookie(self):
        if self.request.session.test_cookie_worked():
            self.request.session.delete_test_cookie()
            return True
        return False

    def get(self, request, *args, **kwargs):
        """
        Same as django.views.generic.edit.ProcessFormView.get(), but adds test cookie stuff
        """
        self.set_test_cookie()
        return super(LoginView, self).get(request, *args, **kwargs)

and urls:

url(r'^login/$', LoginView.as_view(), name='login'),

This solved all my troubles... about loggin and logiing off on...

the login and logout signals just working fine:

from django.contrib.auth.signals import user_logged_out, user_logged_in

# Note, these login and logout signals are registered in imamstats views
def iam_logged_out_actions(sender, user, request, **kwargs):
    try:
        # ... do my logging out actiosn (stats etc.)
    except Exception, e:
        logger.error("Logging logout action error: %s" % e)

# Note, these login and logout signals are registered in imamstats views
def iam_logged_in_actions(sender, user, request, **kwargs):
    try:
        # ... do my log in stats etc. things
    except Exception, e:
        logger.error("Logging login action error: %s" % e)

browsing to stackoverflow... (did another search)

I found this one: .... see django.contrib.auth.logout in Django ..

But is is even worse.... I found this... astonished... but explains it all: Django, Logout_URL doesn't redirect well

The I found out it's a won't fix bug (@##$%%) not allowed to curse on christmas eve....

So the solution to do my custom stuff is in the signals in stead of using my own view. Do the default view and redirect... and use this documentation to create a signal.. https://docs.djangoproject.com/en/dev/topics/auth/#login-and-logout-signals

Adding the signals is quite easy, i put it in models.py off my main app (iamapps):

import logging
from django.contrib.auth.signals import user_logged_out
from django.contrib.auth.signals import user_logged_in
logger = logging.getLogger(__name__)

def iam_logged_out_actions(sender, user, request, **kwargs):
    #whatever...
    logger.debug("Logging out: user = %s" % user)

user_logged_out.connect(iam_logged_out_actions)

def iam_logged_in_actions(sender, user, request, **kwargs):
    #whatever...
    logger.debug("Logging in: user = %s" % user)

user_logged_in.connect(iam_logged_in_actions)

This works....however it does not solve the broken pipe which I think might cause the failure on the logging out... so logging out in firefox still fails... and in chrome it works... Logging out from django admin page works in firefox.. and the signal has another pro: also from logging out in the admin interface, the signal is being called...

for logging out i use now this urls.py:

    url(r'^logout/$', 'django.contrib.auth.views.logout',  {'next_page': '/'}, name='iamapps.logout'),

Tags:

Django

Logout