0

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 ?

1 Answer 1

1

If the user already has a picture and they don't choose a new image via the input, is there a reason to send the URL back to the server? The server could look it up from the database if it really needs it. And if this is an update profile view, then you don't need to do anything and can ignore it not being sent back.

Sign up to request clarification or add additional context in comments.

4 Comments

Hi, Thanks for reverting back. It's a update profile page, and using FormData, I am sending profile picture along with other information using .append() method. But if for the next time, I don't want to update profile picture but just the text in the profile then I get this error django.utils.datastructures.MultiValueDictKeyError: 'file' Is there any way I can make it work even if the fd['file'] is Null.
You should check if the key exists in request.FILES before accessing it via if 'file' in request.FILES or you can use .get() which will default to None if it doesn't exist.
Thanks. Done. I want to confirm is it a safe way to do it ? Or can you provide me some of your worthy suggestions to improve it ?
What do you mean by "safe way to do it"?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.