I have created a basic app using Django's built in authentication system. I successfully created a User object in the shell using
>>python manage.py createsuperuser.
I then created a basic view, 'UserLogin' along with corresponding serializers/urls, to log an existing user in using the django.contrib.auth authenticate(), and login() functions. Upon testing with the credentials of my created user, the login function seemed to have worked successfully.
To test this, I created another view function, 'CurrentUser' which returns the username of the currently logged in user. However, this view returns the user as empty.
Why would the 'CurrentUser' view be returning no user as logged in? I have attached my code (minus imports) below.
views.py:
class UserLogin(APIView):
def post(self, request, format = None):
serializer = UserLoginSerializer(data=request.data)
if serializer.is_valid():
user = authenticate(username=serializer.validated_data["username"], password=serializer.validated_data["password"])
if user is not None:
login(request, user)
return Response(UserSerializer(user).data, status=status.HTTP_201_CREATED)
return Response("Invalid username/password", status=status.HTTP_401_UNAUTHORIZED)
return Response(serializer.errors, status=status.HTTP_401_UNAUTHORIZED)
class CurrentUser(APIView):
def get(self, request, format = None):
return Response(self.request.user.username)
serializers.py:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'username']
class UserLoginSerializer(serializers.Serializer):
username = serializers.CharField(max_length=300, required=True)
password = serializers.CharField(required=True, write_only=True)
urls.py:
urlpatterns = [
path('login/', views.UserLogin.as_view()),
path('current/', views.CurrentUser.as_view())
]
Any guidance would be much appreciated.
Thanks