简体   繁体   中英

User Registration and Login in Django

I have modified the default User and use this method to register a new User.

class RegisterView(views.APIView):
    def post(self, request, **kwargs):
        location = Location.objects.get(id=kwargs.get('location_id'))
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.save()
            user.location = location
            user.save()
            subject = "Please Activate Your FootTheBall Account!"
            token = self._generate()
            link = HOST + PREFIX + str(user.id) + SUFFIX + token
            message = 'Please use the following link to activate your account.\n\n{}'.format(link)
            from_email = settings.EMAIL_HOST_USER
            to_list = [user.email, 'soumasish@foottheball.com']
            send_mail(subject, message, from_email, to_list, fail_silently=True)

            Token.objects.create(user=user, token=token)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

This works fine and the User is registered in the database. I have verified that.

Now I call this method to login the User.

class LoginView(views.APIView):
    def post(self, request):
        user = authenticate(
            email=request.data.get("email"),
            password=request.data.get("password")
        )
        if not user:
            return Response({
                'status': 'Unauthorized',
                'message': 'Email or password incorrect',
            }, status=status.HTTP_401_UNAUTHORIZED)
        login(request, user)
        return Response(UserSerializer(user).data)

Despite providing the correct email and password it can't find the user and authenticate method fails. What am I doing wrong here?

If you are using the default User model from Django auth, then users should be logged in using username and password , not email and password .

Your serializer (which I'm assuming is a ModelSerializer over the User model) saves, so the username field is being sent over, but you are not authenticating with it.

There are ways for you to login with email:

  1. Creating a custom User model, which is somewhat cumbersome.
  2. Writing an authentication backend, which is really simple if you follow the docs .

EDIT: I just read the first line, when you said you customized the User model. If that so, make sure you defined the USERNAME_FIELD attribute of your class to be email

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM