简体   繁体   中英

Unable to use Django Authenticate

I am receiving this error:

TypeError at /auth/
authenticate() missing 1 required positional argument: 'request'

I am using Django and also Django Rest Framework.

The HTTP POST looks like this:

{
    "username": "HelloUser",
    "password": "Hello123"
}

VIEW

@csrf_exempt
@api_view(['POST'])
def authenticate(self, request):
    print(request.data)
    user = authenticate(username=request.data['username'], password=request.data['password'])
    if user is not None:
        return Response({'Status': 'Authenticated'})
    else:
        return Response({'Status': 'Unauthenticated'})

URLS

urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'create/', views.create),
    url(r'retrieve/', views.retrieve),
    url(r'auth/', views.authenticate),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

Firstly you should not use the name of the view as authenticate as it is getting mixed with Django auth's authenticate And second, you don't need self parameter in authentication view ie def authenticate_user(request) Update your code like this:

VIEW

from django.contrib.auth import authenticate

@csrf_exempt
@api_view(['POST'])
def authenticate_user(request):
    print(request.data)
    user = authenticate(username=request.data['username'], password=request.data['password'])
    if user is not None:
        return Response({'Status': 'Authenticated'})
    else:
        return Response({'Status': 'Unauthenticated'})

And your urls.py will be updated as per the view's name:

URLS

urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'create/', views.create),
    url(r'retrieve/', views.retrieve),
    url(r'auth/', views.authenticate_user),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM