[Fixed]-How to autologin after signup using Django Rest Framework?

0👍

This finally work:

class UserList(generics.ListCreateAPIView):
    queryset = MyUser.objects.all()
    serializer_class = UserSerializer
    permission_classes = (IsAuthenticatedOrCreate,)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        new_user = authenticate(email=request.POST.get('email'),
            password=request.POST.get('password'),
            )
        if new_user is not None:
            if new_user.is_active:
                django_login(request, new_user)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

1👍

I think the problem is that you are returning a user object directly, I think it should be as follows:

 from rest_framework import status
 class UserList(generics.ListCreateAPIView):
    queryset = MyUser.objects.all()
    serializer_class = UserSerializer
    permission_classes = (IsAuthenticatedOrCreate,)

    def create(request, *args, **kwargs):
        user = MyUser.objects.create(
            user_name=request.POST.get('user_name'),
            email=request.POST.get('email'),
        )
        user.set_password(request.POST.get('password'))
        user.save()
        user = authenticate(user_name=request.POST.get('user_name'), password=request.POST.get('password'))
        login(request, user)
        serializer = UserSerializer(user)
        return Response(serializer.data, status=status.HTTP_201_CREATED)

Update
I’ve updated the code above regarding this from the documentation.

Calling authenticate() first

When you’re manually logging a user in, you must successfully
authenticate the user with authenticate() before you call login().
authenticate() sets an attribute on the User noting which
authentication backend successfully authenticated that user (see the
backends documentation for details), and this information is needed
later during the login process. An error will be raised if you try to
login a user object retrieved from the database directly.
https://docs.djangoproject.com/en/1.9/topics/auth/default/#how-to-log-a-user-in

Leave a comment