djangocookiesauthenticationdjango-logindjango-upgrade

I'm not able to login after django version upgrade


I'm trying to upgrade an old code from django 1.5 to 1.8 for a client. The project use django.contrib.auth.views.login to verify the login. the urls.py looks as follow:

urlpatterns = patterns('',
    url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'accounts/login.html', 'authentication_form': LoginForm}, name="login"),
    url(r'^accounts/logout/$', 'django.contrib.auth.views.logout', {'template_name': 'accounts/logged_out.html'}, name="logout"),
)

Here is the LoginForm class:

class LoginForm(forms.Form):
    username = forms.CharField(label=_("Username"), max_length=120)
    password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)

    def __init__(self, request=None, *args, **kwargs):
        self.request = request
        self.user_cache = None
        super(LoginForm, self).__init__(*args, **kwargs)

    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if self.request:
            if not self.request.session.test_cookie_worked():
                raise forms.ValidationError(_("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in."))

        return self.cleaned_data

and here is the list of the middlewares:

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',

    'apps.facebook.middleware.FacebookMiddleware',
)

Before the upgrade I was able to login, but after upgrading I'm no longer able to login. I got the following non-field error:

Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in.

If I downgrade to django 1.5 I can login again. How can I solve the problem and why the login is not working in django 1.8.


Solution

  • Remove the cookie test from your login form, it isn't necessary. The check was removed from the Django login form in Django 1.7 (release notes).

    You have CSRF protection enabled, which already ensures that cookies are enabled.

    It's not clear why you are defining your own login form, instead of using the built in form. Using your own form means you hit problems like this, and miss out on new features like the confirm_login_allowed hook.