views:

60

answers:

1

Hay, i have a model which saves 2 images

class Picture(models.Model):
    picture = models.ImageField(upload_to=make_filename)
    thumbnail = models.ImageField(upload_to=make_thumb_filename)
    car = models.ForeignKey('Car')
    created_on = models.DateField(auto_now_add=True)
    updated_on = models.DateField(auto_now=True)

    def save(self):
        super(Picture, self).save()
        size = 200, 200
        filename = str(self.thumbnail.path)
        image = Image.open(filename)
        image.thumbnail(size, Image.ANTIALIAS)
        image.save(filename)

As you can see i have overwrote the save() method I'n my view i have a simple try, except block, which checks for IOErrors (which are raised if a file other than an image is uploaded)

def upload(request):
    car = Car.objects.get(pk=1)
    try:
        picture = Picture(picture=request.FILES['image'], thumbnail=request.FILES['image'], car=car)
        picture.save()
    except IOError:
        return HttpResponseRedirect("/test/")

However, the exception is raised, but the files are still written to the server (and db)

Any ideas how to make sure files dont get written if the IOError is raised?

EDIT

Fixed by writing a custom method

def is_accectable_file(filename):
    extension = filename.split('.')[-1]
    acceptable_filetypes = ['jpeg','jpeg','gif','png']
    if extension in acceptable_filetypes:
        return True
    else:
        return False

Then exiting my model to

class Picture(models.Model):
    picture = models.ImageField(upload_to=make_filename)
    thumbnail = models.ImageField(upload_to=make_thumb_filename)
    car = models.ForeignKey('Car')
    created_on = models.DateField(auto_now_add=True)
    updated_on = models.DateField(auto_now=True)

    def save(self, *args, **kwargs):
        if is_accectable_file(self.picture.name):
            super(Picture, self).save(*args,**kwargs)
            size = 200, 200
            filename = str(self.thumbnail.path)
            image = Image.open(filename)
            image.thumbnail(size, Image.ANTIALIAS)
            image.save(filename)
            return True
        else:
            return False

and my view to

def upload(request):
    car = Car.objects.get(pk=1)
    try:
        picture = Picture(picture=request.FILES['image'], thumbnail=request.FILES['image'], car=car)
        if picture.save():
            return HttpResponse("fine")
        else:
            return HttpResponse("invalid type")
    except:
        return HttpResponse("no file")
+1  A: 

The code that (I assume) throws the IOError is being run after you call the super(Picture,self).save() method. Because of this, the picture getting written to the database even if the exception is thrown.

You just need to move the super call to after the setup code.

As an aside, if you're overriding save I'd recommend doing it as follows:

def save(self,*args,**kwargs):
    ...
    super(Picture, self).save(*args,**kwargs)

Otherwise you'll get an exception in any case where Django is passing in arguments to save (and I believe there are a few cases where it does, at least in the admin).

Matthew Christensen
Thanks for this. I've amended my code and added the super call AFTER it does all the image processing, however nothing gets uploaded, and no exception is called.
dotty
If it were me, the next thing I'd do is add a print statement between each line so you can be sure it's doing what you think it's doing.
Matthew Christensen
Can i do print's within a model?
dotty
As long as you're running devserver, yup! (Take them out before deploying to prod).
Matthew Christensen
Right got it working thanks to a custom method (see original question)
dotty
Not to nitpick but you really probably want to use a Form for the validation -- there's nothing wrong with how you did it, but the "silent fail" of the save() method may cause you grief later. Better to validate with a form and have the save method throw something if wrong. Anyway, good luck!
Matthew Christensen