我从 Traversy Media 的 youtube 上学习了关于 Redox 和 Django 的教程。我跟着教程一起学习,现在我不知道它是否被诅咒了。
curl http://localhost:8000/api/auth/login/ -d \
'{"username": "Tom", "password": "PassWord@321"}' \
-H "Content-type: application/json" -X POST
通过这样做,我需要获取用户和相应的令牌,但我得到的是
{"detail":"Authentication credentials were not provided."}
我做了什么=>
# settings.py
INSTALLED_APPS = [
'leads',
'rest_framework',
'frontend',
'accounts',
'knox',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": ("knox.auth.TokenAuthentication", ),
}
# serializers.py
class LoginSerializer(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField()
def validate(self, data):
user = authenticate(**data)
if user and user.is_active:
return user
raise serializers.ValidationError("Incorrect Credentials")
# api.py
class LoginAPI(generics.GenericAPIView):
serializer_class = LoginSerializer
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data = request.data)
serializer.is_valid(raise_exception = True)
user = serializer.validated_data
_, token = AuthToken.objects.create(user)
return Response({
"user": UserSerializer(user, context = self.get_serializer_context()).data,
"token": token
})
# leadmanager/urls.py
urlpatterns = [
path("api/auth/", include("accounts.urls")),
]
# accounts/urls.py
urlpatterns = [
path("login/", LoginAPI.as_view()),
]
不知道是不是被压坏了。