I had to create a fd=new FormData()
object and use the [.append()][1]
method before sending it through axios to my Django API, otherwise I receive a 400 error.
In my backend the profile image is related through a OneToOne relationship to the user model. Therefore it is serialized as a nested object and expects this for the put request to work.
All changes to the state within the frontend are done with the this.setState
method. I believe important part is the handleSubmit method at the end.
First my axios put request:
export const PutUser=(data)=>(dispatch,getState)=>{
dispatch({type: AUTH_USER_LOADING});
const token=getState().auth.token;
axios(
{
¦ method:'put',
¦ url:`https://<xyz>/api/account/user/`,
¦ data:data,
¦ headers:{
¦ ¦ Authorization: 'Token '+token||null,
¦ ¦ 'Content-Type': 'multipart/form-data',
¦ }
})
¦ .then(response=>{
¦ ¦ dispatch({
¦ ¦ ¦ type: AUTH_USER_PUT,
¦ ¦ ¦ payload: response.data,
¦ ¦ });
¦ })
¦ .catch(err=>{
¦ ¦ dispatch({
¦ ¦ ¦ type:AUTH_USER_PUT_ERROR,
¦ ¦ ¦ payload: err,
¦ ¦ });
¦ })
}
My handleSubmit method needs to create the following json object, where the image attribute gets replaced by the actual user input:
user:{
username:'charly',
first_name:'charly',
last_name:'brown',
profile:{
image: 'imgurl',
}
}
Here is my handleSumit method inside the component:
check append
handleSubmit=(e)=>{
¦ e.preventDefault();
¦ let fd=new FormData();
¦ fd.append('username',this.state.username);
¦ fd.append('first_name',this.state.first_name);
¦ fd.append('last_name',this.state.last_name);
¦ if(this.state.image!=null){fd.append('profile.image',this.state.image, this.state.image.name)};
¦ this.props.PutUser(fd);
};