Answer the question
In order to leave comments, you need to log in
React - Django, how to add an avatar?
Good evening, you need to add an avatar, on the front there is an input c type file and a button to send to the server.
On the server, I read the parameter and add the user model to the avatar field. I get an error title is not serializable - nature_gora.jpg> is not JSON serializable
<input type="file" onChange={this.fileChangedHandler} />
<button onClick={this.uploadHandler}>Upload!</button>
fileChangedHandler(e) {
this.setState({selectedFile: e.target.files[0]})
}
uploadHandler() {
console.log(this.state.selectedFile);
axios.post("/api/add_user_avatar/", {
avatar: this.state.selectedFile.name
})
.then((res) => {
this.setState({showUploadInput: false})
})
.catch(error => {
console.log(error);
});
}
@csrf_exempt
def add_user_avatar(request):
if request.method == "POST":
user = UserAccount.objects.get(id=request.user.id)
data_unicode = request.body.decode("utf-8")
data = json.loads(data_unicode)
user.avatar = "nature_gora.jpg"
user.save()
return JsonResponse({
"avatar": user.avatar
}, safe=False)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question