[Django]-Invalid file when uploading form in Django with a file field

2πŸ‘

βœ…

It’s common practice to render same template if form is not valid, to see error messages on the web page, so instead of return HttpResponse(profilePicForm.errors) you shoud do something like this:

if profilePicForm.is_valid():
        return HttpResponse("<h1>Valid</h1>")
        profilePic = ProfilePictures()
        query = UserInfo.objects.filter(id=id)
        for user in query:
            profilePic.user = user
            break
        profilePic.profile_pic = profilePicForm.cleaned_data['profile_pic']
        profilePic.save()
        return redirect('newsfeed:profile')
    else:
        return render(request, 'template.html', {'profilePicForm': profilePicForm})

Also for file uploading you should add to the form enctype="multipart/form-data":

<form action="{% url 'newsfeed:uploadProfilePic' %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ profilePicForm.as_p }}
    <button type="submit">Upload</button>
</form>

Leave a comment