我收到此错误:
TypeError at /auth/
authenticate() missing 1 required positional argument: 'request'
我正在使用Django和Django Rest Framework。
HTTP POST如下所示:
{
"username": "HelloUser",
"password": "Hello123"
}
查看
@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'))
]
答案 0 :(得分:2)
首先,您不应将视图名称用作身份验证,因为它与Django auth的身份验证混合在一起 其次,您在身份验证视图中不需要 self 参数,例如 def authenticate_user(request) 像这样更新您的代码:
查看强>
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'})
您的urls.py将根据视图的名称进行更新:
<强> 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'))
]