[Answered ]-Django: Why is the Image Field not working

1👍

There are two problems here: if you upload files, you need to specify enctype="multipart/form-data":

form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form }}
    <button type="submit">Upload</button>
</form>

furthermore you need to pass both request.POST and request.FILES to the form:

def photo_view(request):
    try:
        profile = request.user.userimage
    except UserImage.DoesNotExist:
        profile = UserImage(user=request.user)
    
    if request.method == 'POST':
        form = UserImageForm(request.POST, request.FILES, instance=profile)
        if form.is_valid():
            form.save()
            return redirect('/dashboard/user/profile')
    else:
        form = UserImageForm(instance=profile)

    return render(request, 'photo.html', {'form': form})

Leave a comment