序列化程序给出空的 OrderedDict(数据为 None)

Serializer giving empty OrderedDict (data is None)

请注意,email基本上是这里的用户名,以免混淆,在serializer.py中我调试了数据,但似乎user给我None

serializer.py

class LoginSerializer(serializers.Serializer):
    def validate(self, data):
        email = data.get("email") 
        print(f" email here : {email}") #empty string
        password = data.get("password") #empty string
        user = authenticate(username=email, password=password)
        print(f"{user} username serializer ")
        print(f"this is data : {data}") #None
        if user is not None:
            return data
        raise serializers.ValidationError("Incorrect Credentials")

views.py

class LoginView(views.APIView):
    def post(self, request):
        data = serializers.LoginSerializer(data=request.data)
        print(data.is_valid()) #False
        print(data.errors) # HEEERE::: LoginSerializer(data={'email': 'someemail', 'password': 'somepassword'}):
        print(f" HEEERE::: {data}")
        if self.request.method == 'POST':
            if data.is_valid():
                auth = authenticate(
                    username=data.validated_data['email'].value, password=data.validated_data['password'].value)
                print(f"auth:: {auth}")
                if auth is not None:
                        login(request, auth)
                        request.session['user_id'] = auth.id
                        print("test")
                        return redirect("/ticket")

                else:
                    return HttpResponse("Invalid Credentials")
            else:
                return HttpResponse("Data not being validated :O")

在前端(React):

import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { login } from '../actions/auth';
import axios from 'axios';

function Login(){
    const [login,setLogin] = useState({
        email: '',
        password:''
    });
    const { email, password } = login;
    function handleChange(e){
        console.log(e.target.value);
        setLogin({
            ...login,
            [e.target.name]: e.target.value
        });

    }
    function handleSubmit(e){
        e.preventDefault();
        axios.post(' http://127.0.0.1:8000/login/', login)
        console.log(login);

    }
    return (
        <div className="container">
        <form method='post' onSubmit={handleSubmit}>
            <h1>Login</h1>
            <label>
                Email:
                <input type='text' name = 'email' value={email} onChange={e=>handleChange(e)} required/>

            </label>
            <label>
                Password:
                <input type='password' name = 'password' value={password} onChange={e=>handleChange(e)} required/>
            </label>
            <button type='submit'>Login</button>
        </form>
            <p className='mt-3'>
                Don't have an Account? <Link to='/signup'>Sign Up</Link>
            </p>
        </div>
    );
};

const mapStateToProps = state => ({
    isAuthenticated: state.auth.isAuthenticated
});


export default Login

请注意,当我按 Login 时,我在 cmd 上得到 LoginSerializer(data={'email': 'someemail', 'password': 'somepassword'}):,(查看 print(f" HEEERE::: {data}"))在 views.py 我不确定序列化器在这里是如何工作的,感谢任何帮助。

您的序列化程序未定义任何字段。请查看DRF教程

https://www.django-rest-framework.org/api-guide/serializers/#declaring-serializers