2

I have been trying to implement a image upload for changing avatar for individual users. The problem I have right now is that it never uploads to the folder. It works from the admin but it doesn't work on the template I've created

views.py

if 'avatar_upload' in request.POST:
    avatar_form = UserAvatarForm(request.POST, request.FILES, instance=request.user.get_profile())
    if avatar_form.is_valid():
        avatar_form.save()
        return HttpResponse(request.POST['avatar'])
    return HttpResponse("Failed")

I've changed the code for viewing the outputs. I get the file name in the POST. But I don't have anything in the request.FILES. So I'm guessing it is a problem there, and I haven't found out so far what the problem could be. Or could it be some problem elsewhere?

template*

<form action="" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {% for item in avatar_form %}<p>{{ item.label }}: {{ item }}</p>
    {% endfor %}
    <input type="submit" value="Upload avatar" name="avatar_upload">
</form> 
starcorn
  • 8,261
  • 23
  • 83
  • 124

1 Answers1

5

Have you set enctype="multipart/form-data" in form in the template?

okm
  • 23,575
  • 5
  • 83
  • 90
  • @starcorn that's weird, have you reload the server and fresh the page before uploading? Getting filename in `request.POST` instead of in `request.FILES` is typically caused by missing `multipart/form-data`. – okm May 02 '12 at 17:02
  • Seems to be working now, but I get `InMemoryUploadedFile` error instead. I thought Django would handle the file upload in the background. But it seems I have to write code to save it the `MEDIA_FOLDER`, and also update the avatar url for the user as well? – starcorn May 02 '12 at 17:10