Python Forum

Full Version: Django problem with files
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
When working on the test server I am able to delete old user profile images when a new one is uploaded, however when attempting this on a staging server the files do not get deleted. Using apache2 server .Any help is great. Relevant code.
views.py

import os

@login_required
def edit_profile(request):

    if request.method == 'POST':

        if request.POST.get('image') == '':
            pass
        else:
            old_img = request.user.profile.image
            if os.path.exists('media/' + str(old_img)):
                del_img = 'media/' + str(old_img)
                os.remove(del_img)
            else:
                pass
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(request.POST, request.FILES,  instance=request.user.profile)
        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request, 'Your profile has been updated.')
            return redirect('profile')
    else:
        u_form = UserUpdateForm(instance=request.user)
        p_form = ProfileUpdateForm(instance=request.user.profile)

    context = {
        'u_form': u_form,
        'p_form': p_form,
    }
    return render(request, 'users/edit_profile.html', context)
Well this is what I came up with to work. Probably not the best solution but, I'm learning more.
Used the os.path.isfile for testing then took it out.

@login_required
def edit_profile(request):
    curr_img = request.user.profile.image.url # Getting the current image


    if request.method == 'POST':

        if request.POST.get('image') == '': #Checking to see if the user changed image or left blank
            pass
        else:
            os.remove('/path/to/top/level/folder' + str(curr_img)) # What I had to use to get the old file removed


        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(request.POST, request.FILES,  instance=request.user.profile)
        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request, 'Your profile has been updated.')
            return redirect('profile')
    else:
        u_form = UserUpdateForm(instance=request.user)
        p_form = ProfileUpdateForm(instance=request.user.profile)

    context = {
        'u_form': u_form,
        'p_form': p_form,
    }
    return render(request, 'users/edit_profile.html', context)