0

Currently I'm trying to build a function that users can change their profiles, including email, names and photos. However, I have succeeded in changing email and names but I failed to change photos. My initial idea is that firstly I get the photo path and then pass the path to view.py.

My html code is like:

<input type="file" id="ava_up" name="ava_up" accept="image/png, image/jpeg, image/gif, image/jpg" /> 

My ajax code is:

$(document).on('submit', '#profile_edit', function (e) { e.preventDefault(); var usr_nickname = $('#e_nickname').val(); var pattern = "%"; var res = usr_nickname.match(pattern) if(res){ $('#error_info').html("<b>Your nickname should not contain %.</b>") return; } var usr_email = $('#e_email').val(); var usr_photo = $('#ava_up').val(); $.ajax({ type:'POST', url:'./', data:{ async: false, avatar:usr_photo, nickname:usr_nickname, email:usr_email, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:function (response) { var t = $.parseJSON(response) if (t.code == 1){ $('#error_info').html("<b></b>") $('#done').modal('show') } else if (t.code == -2){ $('#error_info').html(t.message) } else { $('#error_info_2').html(t.message) } //window.location.reload() }, }) }) 

my View.py is:

def edit_usr_profile(request): result = collections.OrderedDict() result['code'] = "" result['message'] = "" user = request.user objs = UserProfile.objects.filter(usr=user) usr_objs = UserProfile.objects.get(usr=user) if request.method == 'POST': if request.is_ajax(): try: usr_objs.avatar = request.FILES.get('avatar') usr_objs.nickname = request.POST.get('nickname') usr_objs.email = request.POST.get('email') usr_objs.save() result['code'] = "1" result['message'] = "" except Exception as e: if str(e) == "'avatar'": result['code'] = "-1" result['message'] = "Failed to upload photo." else: result['code'] = "-2" result['message'] = "The nickname you entered exists. Please try another one." return JsonResponse(json.dumps(result), safe=False) return render(request, 'account/edit_profile.html', {'objs':objs, 'resultInfo':result}) 

I just tried to alert the photo path but it returned "C:\fakepath\photo.jpg". Then I searched on Google and people said that is because of the browser security. So I wonder if anyone have suggestions about how can I upload (or pass the full path of images to View.py) photos?

I'll be very appreciated if you can help me!

1

2 Answers 2

0

You are not sending actual image with .val(), just name of the files. To send image via ajax you will need to use FormData to send form:

edit_profile.html:

<form id="profile_edit"> {% csrf_token %} <input type="text" id="e_nickname" name="email"/> <input type="text" id="e_email" name="nickname"/> <input type="file" id="ava_up" name="avatar" accept="image/png, image/jpeg, image/gif, image/jpg"/> <button type="submit">submit</button> </form> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> <script> $(document).on('submit', '#profile_edit', function (e) { e.preventDefault(); var usr_nickname = $('#e_nickname').val(); var pattern = "%"; var res = usr_nickname.match(pattern) if (res) { $('#error_info').html("<b>Your nickname should not contain %.</b>") return; } $.ajax({ type: 'POST', url: './', data: new FormData(this), processData: false, contentType: false, success: function (response) { var t = $.parseJSON(response) if (t.code == 1) { $('#error_info').html("<b></b>") $('#done').modal('show') } else if (t.code == -2) { $('#error_info').html(t.message) } else { $('#error_info_2').html(t.message) } //window.location.reload() }, }) }) </script> 
Sign up to request clarification or add additional context in comments.

Comments

0

let's say u have form like <form id="myForm"> ur js should like follow

$(document).on('submit', '#myForm', function (e) { e.preventDefault(); // validations let formData = new FormData($("#myForm")[0]); $.ajax({ url: url, type: 'post', contentType: false, processData: false, data: formData }) .done(function(){ // success }) .fail(function(){ // fail }) }); 

In the View Handle Upload just like normal flow.

form = MyModelForm(request.POST, request.FILES) form.save() 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.