S
S
Sergey Alekseev2018-05-03 17:28:23
Django
Sergey Alekseev, 2018-05-03 17:28:23

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)

What is missing on the backend?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
planc, 2018-05-03
@serj2000

you need to create a FormData object in js, push a file into it, and work on the backend as with a form
. What is a convenient, beautiful file uploader for vue?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question