Home > Software engineering >  Authentication returns None in django rest frame work API
Authentication returns None in django rest frame work API

Time:10-18

views.py

@api_view(['POST'])
def login(request):
    data = {}
    email = request.data.get('email')
    password = request.data.get('password')
    user = authenticate(email = email, password = password)
    U = User.objects.get(email=email)
    if user is not None:
        login(request, user)
        data['response'] = 'successfully logged in'
    elif Userprofile.objects.filter(email=email).exists() == False:
        data['response'] = 'user does not exist'
    elif U.is_active == False:
        data['response'] = 'Please verify your email'
    else:
        data['response'] = 'invalid password'
    return JsonResponse(data)
otp=random.randint(11111,99999)
@api_view(['POST'])
def signup(request):
    serializer = UserprofileSerializer(data=request.data)
    data = {}
    if serializer.is_valid():
        name = serializer.validated_data['name']
        email = serializer.validated_data['email']
        phone_number = serializer.validated_data['phone_number']
        password = make_password(serializer.validated_data.get('password'))
        account = Userprofile.objects.create_user(name = name, email = email, phone_number = phone_number, password = password)
        data['response'] = 'successfully registered a new user'
        send_mail(
            'Welcome to Trycompound',
            'Your OTP is ' str(otp),
            EMAIL_HOST_USER,
            [email],
        )
        user = User.objects.get(email=email)
        user.otp = otp
        user.save()
    else:
        data = serializer.errors
    return JsonResponse(data)

I really can'f figure what's wrong because I have actually done these with the normal templates and when i tried it with the django rest framework, I am unable to login because authenticate is returning 'None'. and yes User is active, it says 1 in the database.

CodePudding user response:

authenticate function will return none if credentials are invalid. It will return the user object if the credentials are valid. Click here for more info and it takes username and password as parameters

CodePudding user response:

There is not problem with this code, The problem is with the creation of users, I can't get to set the password properly.

  • Related