0

In my aplication, the users can change their profile data, like full name, gender, profile image and other stuff. The problem is when the user want to keep the same profile picture and the file input is empty. How do I support that in my view.

Here is my html updateProfile.html

<form action="{% url 'updateprofile' %}" enctype="multipart/form-data" method="POST">{% csrf_token %}
  <input type="file" id="logofile" name="avatar" accept="image/gif, image/jpeg, image/png" value="">
  <input type="text"name="full_name">
  <input type="date"name="birthdate">
</form>

Here is my views.py updateprofile

def updateprofile(request):
    #HERE IS WHERE I CHECK IF I CHANGE THE IMAGE OR NOT BUT THIS NOT WORKS IF THE FILE INPUT IS EMPTY
    if request.FILES['avatar']:
        avatar = request.FILES['avatar']

    full_name=request.POST['full_name']
    birth_date= request.POST['birthdate']

    c = user.objects.get(id=request.session['account_id'])
    c.full_name = full_name
    c.avatar = avatar
    c.save()
    return redirect('userprofile')

If I change the file in the file input everything works well. But If I don't upload a new Image and leave the file input in blank I have an error. How do I check if there is file or not in the POST request? please help

1 Answer 1

1

You can use if request.FILES.get('avatar') instead of if request.FILES['avatar'] this will not raise the KeyError.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.