mercredi 30 juin 2021

'No active account found with those credentials' when trying to log in with Django REST + Simple JWT

I'm trying to set up this API with user authentication but I keep getting the error message in the title when trying to log in. Registration seems to work and the super user can log in. I believe it is due to the password hashing, because when I go to the admin panel, every user has the same message: 'Invalid password format or unknown hashing algorithm.' except the super user (which I created in the terminal). Have I made a mistake in the user creation part?

Serializers.py

from rest_framework import serializers
from rest_framework.permissions import IsAuthenticated
from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from django.contrib.auth.hashers import make_password

class RegisterSerializer(serializers.ModelSerializer):
    class Meta:
        model = User 
        fields = ('id', 'username', 'password')

    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        return user

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

    def validate(self, data):
        user = authenticate(**data)
        if user and user.is_active:
            return user

Views.py

from django.shortcuts import render
from rest_framework.response import Response
from rest_framework import generics, permissions, mixins
from django.contrib.auth.models import User
from .serializers import RegisterSerializer

class RegisterAPI(generics.GenericAPIView):
    serializer_class = RegisterSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        return Response({
        "message": "User created successfully!"
        })

Settings.py

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'api',
'rest_framework_simplejwt', 
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication'
        ]
    }



Aucun commentaire:

Enregistrer un commentaire