Categories
Mastering Development

Django + React Able to create new user in database, but token-auth returns 400 bad request

So I have an app that I’m writing. It’s working, for the most part, so far. I only currently have a login and signup setup, with a ‘homepage’ that just has a logout button and some text on it so I can test.

When I do signup, it posts the user to the database, but then I get this:

Bad Request Image

Here is my Instructor Model:

class Instructor(AbstractUser):
    displayname = models.CharField(max_length=80, blank=True, null=True)
    email_address = models.EmailField(blank=True, null=True)
    grade_taught = models.IntegerField(default = 0)
    room_number = models.IntegerField(default = 0)

Serializer(Instructor and with Token):

class InstructorSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Instructor
        fields = [
            'id',
            'username',
            'email_address',
            'displayname',
            'grade_taught',
            'room_number'
        ]

class InstructorSerializerWithToken(serializers.ModelSerializer):
    
    token = serializers.SerializerMethodField()
    password = serializers.CharField(write_only = True)

    def get_token(self, obj):
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(obj)
        token = jwt_encode_handler(payload)

    def create(self, validated_data):
        password = validated_data.pop('password', None)
        instance = self.Meta.model(**validated_data)
        if password is not None:
            instance.set_password(password)
        instance.save()
        return instance

    class Meta:
        model = models.Instructor
        fields = [
            'token',
            'username',
            'password',
            'email_address',
            'displayname',
            'grade_taught',
            'room_number'
        ]

Related Views:

class InstructorList(APIView):

    permission_classes = (permissions.AllowAny,)

    def post(self, request):

        serializer = serializers.InstructorSerializerWithToken(data = request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status = status.HTTP_201_CREATED)
        return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST)

class InstructorViewSet(viewsets.ModelViewSet):
    queryset = models.Instructor.objects.all()
    serializer_class = serializers.InstructorSerializer

cors headers:

CORS_ALLOWED_ORIGINS = [
    'http://127.0.0.1:8000',
    'http://localhost:3000',
]

CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]

CORS_ALLOW_HEADERS = [
    'accept',
    'Accept',
    'accept-encoding',
    'authorization',
    'Authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    "*"
]

JWT Auth settings:

JWT_AUTH = {
    'JWT_RESPONSE_PAYLOAD_HANDLER': 'diceapp.utils.my_jwt_response_handler',
    'JWT_VERIFY_EXPIRATION': False,
}

Edit: Adding the request that causes the bad return.

const handleLogin = (username, password) => {
        const url = 'http://127.0.0.1:8000/token-auth/'
        fetch(url, {
            method: 'POST',
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({ username: username, password: password })
        })
            .then(res => res.json())
            .then(data => {
                localStorage.setItem('token', data.token);
                props.updateToken(data.token)
            })
            .catch(error => console.log(error))
        history.push('/dice/')
    }

Any help would be appreciated. Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *