WebFaction
Community site: login faq

Hi,

I am new in django and I am having problems with the removal of a file when a user uploads a new one (the old file is no longer useful for the app).

The thing is that when I user wants to update his/her profile picture, my application should remove the old one. I tried this by overriding the save function in my form UserProfileForm, related to the UserProfile model.

I have written the same lines of the save function in the shell console and it seems to work. I also tried to override the save function in the model but I got the same negative result.

I would really appreciate if anyone could give me some advice about what I am doing wrong and how should I fix it! ;)

Thank you in advance, Mario

PS: I am using the django-profiles app. It calls the save function of the form_class, which is actually my UserProfileForm. =)

One portion of my model

class UserProfile(models.Model):
  user = models.ForeignKey(User, unique=True)
  name = models.CharField(max_length=30, null=True)
  image = models.ImageField(upload_to='profile_images', default='default-user.png')

My form for the model

from django import forms
from django.db import models
from django.forms import ModelForm
from myportal.portal.models import UserProfile
from myportal.portal.models import GENDER_CHOICES
from myportal.portal.models import LEVEL_CHOICES
from django.contrib.auth.models import User

from myportal.portal.files import handle_uploaded_file

from os.path import join as isfile
from django.conf import settings
import os

class ProfileForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(ProfileForm, self).__init__(*args, **kwargs)
        try:
            self.fields['email'].initial = self.instance.user.email
            # self.fields['first_name'].initial = self.instance.user.first_name
            # self.fields['last_name'].initial = self.instance.user.last_name
        except User.DoesNotExist:
            pass

    name = forms.CharField(max_length=30, label='Nombre')
    gender = forms.ChoiceField(choices=GENDER_CHOICES, label='Sexo')
    city = forms.CharField(max_length=30, label='Ciudad')
    level = forms.ChoiceField(choices=LEVEL_CHOICES, label='Nivel de juego')
    email = forms.EmailField(label='Correo')
    image = forms.ImageField(label='Imagen', required=False)

    class Meta:
      model = UserProfile
      exclude = ('user',)

    def save(self, *args, **kwargs):
        """
        Update the primary email address on the related User object as well.
        """
        u = self.instance.user
        u.email = self.cleaned_data['email']
        #u.save()
        profile = u.get_profile()
        image_path = settings.MEDIA_ROOT + profile.image.name
        if os.path.isfile(image_path):
            os.remove(image_path)
        profile = super(ProfileForm, self).save(*args,**kwargs)
        handle_uploaded_file(self.cleaned_data['image'])
        return profile

Finally the function handle_uploaded_file, which actually works fine! ;) from PIL import Image as PImage from os.path import join as pjoin from django.conf import settings

def handle_uploaded_file(file):
        #print type(file), "file.name=",file.name
        #print dir(file)
        #destination = open(MEDIA_ROOT + '/images/test.jpg', 'wb+')
        #for chunk in file.chunks():
        #   destination.write(chunk)
        imfn = pjoin(settings.MEDIA_ROOT + 'profile_images/', file.name)
        im = PImage.open(imfn)
        im.thumbnail((150,150), PImage.ANTIALIAS)
        im.save(imfn, "JPEG")

asked 15 Nov '10, 11:48

mariocao
113
accept rate: 0%

You say that it seems to work in the shell. What happens on your site? Do you get any kind of error message, or does it fail silently (ie, it simply fails to delete the old image)?

(15 Nov '10, 12:26) seanf

It simply fails to delete the old image. I have not said it, but if a set "image_path" to a fixed path, e.g. "/home/username/webapss/static_media_app/profile_images/file.png" it deletes my images. It is really strange, but perhaps just something I have overread or forgotten. =S

Thanks for your interest and help! ;)

(15 Nov '10, 12:31) mariocao

Since it is simply failing to delete the image and is not throwing an error, then I suspect that your if os.path.isfile(image_path) test is evaluating to false, probably because image_path is not what you expect it to be at runtime.

permanent link

answered 15 Nov '10, 12:55

seanf
12.2k41836
accept rate: 37%

Hi,

It was true what you said, but the unexpected problem (for me) was while creating a form object in my view with the following line:

form = form_class(data=request.POST, files=request.FILES, instance=profile_obj)

This line made that the image field of my model already points to the new uploaded image. Therefore I could not delete the old one (the path to it was nowhere).

My solution was a workaround! ;) I deleted the old uploaded file by using the delete() function of the ImageField object. Then a saved the form and finally I resized my uplaoded image! ;)

Anyway, thank you very much for your help!!! ;)

if request.method == 'POST':
    #deletes old file in case of new file upload
    form_aux = form_class(data=request.POST, files=request.FILES)
    if form_aux.is_valid() and 'image' in request.FILES:
        profile_obj.image.delete()

    form = form_class(data=request.POST, files=request.FILES, instance=profile_obj)
    if form.is_valid():
        form.save()
        #resizes new file
        if 'image' in request.FILES:
            handle_uploaded_file(profile_obj.image)

        return HttpResponseRedirect(success_url)
permanent link

answered 16 Nov '10, 04:30

mariocao
113
accept rate: 0%

Your answer
toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Question tags:

×909
×29
×22
×1

question asked: 15 Nov '10, 11:48

question was seen: 9,418 times

last updated: 16 Nov '10, 04:30

WEBFACTION
REACH US
SUPPORT
AFFILIATE PROGRAM
LEGAL
© COPYRIGHT 2003-2019 SWARMA LIMITED - WEBFACTION IS A SERVICE OF SWARMA LIMITED
REGISTERED IN ENGLAND AND WALES 5729350 - VAT REGISTRATION NUMBER 877397162
5TH FLOOR, THE OLD VINYL FACTORY, HAYES, UB3 1HA, UNITED KINGDOM