Question

I am having a strange error in django while trying to authenticate my user.

here is the code:

views.py

from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.core.context_processors import csrf
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import authenticate, login

def authenticate(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            # Redirect to a success page.
        else:
            pass
            # Return a 'disabled account' error message
    else:
        pass
        # Return an 'invalid login' error message.

It keeps giving me this error:

Environment:


Request Method: POST
Request URL: http://localhost:8000/authenticate/

Django Version: 1.6.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'neededform')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')


Traceback:
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/core/handlers/base.py" in get_response
  114.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/jarvis/django/web/web/views.py" in authenticate
  26.     user = authenticate(username=str(username), password=password)

Exception Type: TypeError at /authenticate/
Exception Value: authenticate() got an unexpected keyword argument 'username'

I cant comprehend the source of this error. have someone face the same problem ?

Was it helpful?

Solution

The code is using authenticate as a view name. That overwrites the reference to the imported function authenticate.

from django.contrib.auth import authenticate, login
#                               ^^^^^^^^^^^^

def authenticate(request):
#   ^^^^^^^^^^^^

Rename the view:

def other_view_name(request):

Or import the function as different name (also change call to the function):

from django.contrib.auth import authenticate as auth
...

user = authenticate(...) -> user = auth(...)

Or import django.contrib.auth and use the fully qualified name.

import django.contrib.auth
...

user = authenticate(...) -> user = django.contrib.auth.authenticate(...)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top