How to upload image/media file from React to Django API?

1.3k Views Asked by At

I am able to save the data without the image field. I am new to react so don't know pretty much about this type of problems. What is the problem with the image field?? this isn't showing me any error just my image data is not saving. I am sharing all my code it will be really helpful if you guys help me out.

#models.py

class Test(models.Model):
    full_name = models.TextField(max_length=200, blank=True, null=True)
    image =  models.ImageField(null=True, blank=True)
    address = models.TextField(max_length=200, blank=True, null=True)

    def __str__(self):
        return str(self.id)

#views.py

@api_view(['POST'])
def add(request):
    data = request.data
    test = Test.objects.create(
            full_name = data['full_name'],
            address = data['address'],
        )
    serializer = TestSerializer(test, many=False)
    return Response(serializer.data)

#this is screen for react page

import React from 'react';
class Test extends React.Component{
    constructor(){
        super();
        this.state={
            full_name:'',
            image: '',
            address:''
            
        }
        this.changeHandler=this.changeHandler.bind(this);
        this.submitForm=this.submitForm.bind(this);
    }

    // Input Change Handler
    changeHandler(event){
        this.setState({
            [event.target.name]:event.target.value
        });
    }

    // Submit Form
    submitForm(){
        fetch('http://127.0.0.1:8000/api/orders/test',{
            method:'POST',
            body:JSON.stringify(this.state),
            headers:{
                'Content-type': 'application/json; charset=UTF-8',
            },
        })
        .then(response=>response.json())
        .then((data)=>console.log(data));

        this.setState({
            full_name:'',
            image: '',
            address:''
            
        });
    }

    render(){
        return (
            <table className="table table-bordered">
                <tbody>
                    <tr>
                        <th>Full Name</th>
                        <td>
                            <input value={this.state.full_name} name="full_name" onChange={this.changeHandler} type="text" className="form-control" />
                        </td>
                    </tr>

                    <tr>
                        <th>Voucher</th>
                        <td>
                            <input value={this.state.image} name="image" onChange={this.changeHandler} type="file" className="form-control" />
                        </td>
                    </tr>
                    
                    <tr>
                        <th>Address</th>
                        <td>
                            <input value={this.state.address} name="address" onChange={this.changeHandler} type="text" className="form-control" />
                        </td>
                    </tr>
                    <tr>
                        <td colSpan="2">
                            <input type="submit" onClick={this.submitForm} className="btn btn-dark" />
                        </td>
                    </tr>
                </tbody>
            </table>
        );
    }
}

export default Test;
1

There are 1 best solutions below

2
nilay shah On

Kindly remove null=True, blank=True from Test model in image filed.