Home > Software design >  Serializer giving empty OrderedDict (data is None)
Serializer giving empty OrderedDict (data is None)

Time:12-12

please note that email is basically the username here to not get confused, in serializer.py I have debugged the data, but it seem that user is giving me 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")

on frontend side (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

please note that when i press Login i get LoginSerializer(data={'email': 'someemail', 'password': 'somepassword'}): on cmd, (look at print(f" HEEERE::: {data}")) in views.py I am not sure how the serializer is working here, any help is appreciated.

CodePudding user response:

Your serializer doesn't define any fields. Please checkout the tutorial of DRF.

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

  • Related