将数据从React Js发布到Django Rest

时间:2019-02-13 21:31:39

标签: reactjs django-rest-framework

我正在尝试将数据从react js发布到django rest api,但是收到HTTP 400错误的请求错误(“由于语法无效,服务器无法处理该请求。”)

我试图重构我的代码,但我找不到问题所在,在我的代码下面是

class Postjob extends React.Component{
constructor(props){
    super(props);
    this.submitForm=this.submitForm.bind(this);
    this.postedjob=this.postedjob.bind(this);
    this.state={
        Company:0,
        job_title:"",
        job_description:"",
        salary:0,
        job_status:false,
    }
}

submitForm= (evt) =>{
    evt.preventDefault()
    console.log(this.state.Company)
    const form={
        Company: this.state.Company,
        job_title: this.state.job_title,
        job_description: this.state.job_description,
        salary: this.state.salary,
        job_status: this.state.job_status
    };

    this.postedjob(form)

};

postedjob = (payload)=>{


    fetch(`http://127.0.0.1:8000/job/create_job/`,
        {
            method: 'POST',
            body: JSON.stringify(payload),
            headers: {
                'Content-Type': 'application/json'
            }
        }
    ).then(response => response.json())
};

render() {
    return(
        <div>
            <h1>{this.state.currenttask}</h1>
            <form onSubmit={this.submitForm}>

                <input type='number' value={this.state.Company} onChange={e=>this.setState({Company:e.target.value})}/>

              <input type='text' value={this.state.job_title} onChange={e=>this.setState({job_title:e.target.value})}/>


                <input type='text' value={this.state.job_description} onChange={e=>this.setState({job_description:e.target.value})}/>

                <input type='number' value={this.state.salary} onChange={e=>this.setState({salary:e.target.value})}/>

                <button type="submit">Submit</button>

          </form>

        </div>
    )
}

}

Django Side:

Views.py:

lass Companylist(APIView):

 def get(self,request):
   return Response([CompanySerializer(company).data for company in Company.objects.all()])

  def post(self,request):
   payload=request.data
   serializer=CompanySerializer(data=payload)

   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)

Serializers.py:

class CompanySerializer(serializers.ModelSerializer):

class Meta:
    model=Company
    fields='__all__' #to get all fields

def create(self, validated_data):
    company = Company.objects.all(**validated_data)
    return company

def update(self, instance, validated_data):
    for k, v in validated_data.items():
        setattr(instance, k, v)
        instance.save()
    return instance

def validate(self, attrs):
    if not attrs.get('company_name') or attrs.get('company_name') < 10:
        raise ValidationError("Book is too small to read")
    return attrs

我尝试从django api进行发布,并且成功完成,但是当我从react js表单尝试时,它给了我错误,并且我找不到原因。 如果有人能够找到错误原因,将非常感谢。

1 个答案:

答案 0 :(得分:0)

将有效负载序列化为json时,可能是因为类型错误。 您确定一切吗?公司字段是否以大写字母开头在服务器上?应该是数字吗?如果是这样,则在对有效负载进行字符串化时,应注意状态值的类型。

例如,onChange的 event.target.value 中提供的值将具有 string 类型,即使输入类型为数字

您还想看看我创建的CodeSandbox