django - login view in DRF

I have a register view in my django code which works fine:



Working in Django rest framework,



class UserViewSet(viewsets.ReadOnlyModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer

@list_route(methods=['post'])
def register(self, request):
serializer = UserSerializer(data=request.DATA)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


Now I want to add a login view in order to let users login, I wrote something like this, not sure about this:



@list_route(methods=['post'])
def login(self, 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)
return Response(status=status.HTTP_200_OK)
else:
return Response(status=status.HTTP_404_NOT_FOUND)
else:
return Response(status=status.HTTP_401_UNAUTHORIZED)


couple of questions:




does it look okay?
and also, how should I POST to this view? to the register view I POST with json and it works fine.
Will json with the username and password work here as well?

Answers

You login method is not correct using DRF.
For login you haven’t used the serialzers.
Your can go through these api for login,logout etc for clear understanding



Djoser
Djoser library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and it uses token based authentication. This is a ready to use REST implementation of Django authentication system.



django-rest-auth
Django-rest-auth library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management.