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

def register(self, request):
serializer = UserSerializer(data=request.DATA)
if serializer.is_valid():
return Response(, status=status.HTTP_201_CREATED)
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:

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)
return Response(status=status.HTTP_404_NOT_FOUND)
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?


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 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 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.