Search code examples
pythondjangofile-uploaddjango-uploads

Django, upload image error


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


Solution

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