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!