我正在努力构建一个带有 django rest 框架后端的 react 本机应用程序。我已经创建了注册视图集,并且能够使用以下方法从前端成功注册用户:
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSeralizer
我创建了另一个视图集来验证用户的电子邮件和密码,如下所示:
class LoginViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = LoginSeralizer
@detail_route(['POST'])
def login_user(self,request, pk=None):
if request.method == "POST":
email = request.POST.get("email", False)
password = request.POST.get("password", False)
user = authenticate(email=email, password=password)
if user is not None:
if user.is_active:
return Response(user.data, status=status.HTTP_200_OK)
else:
return Response(user.error, status=status.HTTP_400_BAD_REQUEST)
else:
return Response(user.error, status=status.HTTP_400_BAD_REQUEST)
当我尝试从前端访问 url 时,不会调用 detail_route 方法。我收到一个错误的响应 400 错误,指出用户已被创建。我走在正确的轨道上吗?我对 detail_route 方法进行了哪些更改,以便在将 url 传递到 react 本机应用程序的 fetch 方法时从前端调用它?
django 项目中的其余文件如下:url.py:
from django.contrib import admin
from django.conf.urls import url, include
from rest_framework import routers
router = routers.DefaultRouter()
#makes sure that the API endpoints work
router.register(r'api/users', views.UserViewSet)
router.register(r'api/login', views.LoginViewSet)
admin.autodiscover()
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),]
serializer.py:
class UserSeralizer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('username', 'email', 'password')
class LoginSeralizer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('email', 'password')
LoginSeralizer 和 UserViewSet/UserSeralizer 几乎相同。当您登录时,您实际上创建了用户。
阅读有关使用 REST 框架的身份验证方法的信息:http://www.django-rest-framework.org/api-guide/authentication/