I am trying to upload profile picture using Ajax (using FormData) in Django.
Following is the code I used it in html page,
<img src="/media/{{user_profile.picture}}" width="150" height="150" alt="" id="pro_file"/> <input id="upload-file" type="file" name="file"/> and in jQuery (Ajax),
var fd = new FormData(); var vidFileLength = $('#upload-file')[0].files.length; if(vidFileLength === 0){ var files = $('#pro_file').attr('src'); } else{ var files = $('#upload-file')[0].files[0]; } fd.append('file',files); Then I have sent the fd in data attribute in Ajax.
However, in views.py following is my snippet code,
fd = request.FILES try: profile_pic = fd['file'] except KeyError as e: profile_pic = request.POST['file'] profile_pic = str(profile_pic).replace("/media/","") Using this method, my code works but I doubt is it a proper way to do it ? Any suggestions please ?