views:

41

answers:

1

Hay i have a method in my view which uploads an image, the image is then saved to a db object. I want to remove this from my view and either put it in my model or a seperate file.

filename_bits = request.FILES['image'].name.split(".")
filename_bits.reverse()
extension = filename_bits[0]

# create filename and open a destination
filename = '_'+force_unicode(random.randint(0,10000000))+'_'+force_unicode(random.randint(0,10000000))+'.'+force_unicode(extension)
path = 'assests/uploads/'+filename
destination = open(path, 'wb+')

# write to that destination
for chunk in request.FILES['image'].chunks():
    destination.write(chunk)
destination.close()

picture = CarPicture(car=car, path=path, filename=filename)
picture.save()

as you can see it uploads a file (after creating random filenames) then create a carPicture object and saves it.

Any ideas? Could this be done in the model by overwriting the save method?

+2  A: 

You should consider using an ImageField in your model. For example in models.py you would have:

def get_random_filename(car_picture, filename):
    extension = filename.split('.')[-1]
    return u'_%s_%s.%s' % (random.randint(0,10000000),
                           random.randint(0,10000000),
                           extension)

class CarPicture(models.Model):
    title = models.TextField()
    image = models.ImageField(upload_to=get_random_filename)

And in your views you would just have:

picture = CarPicture(title="Some Title", image=request.FILES['image'])
picture.save()

This will store the image to disk, using the randomly generated filename, and set the image field in the database to the path of the image. You can also get the url for the image with:

picture.image.url()

so a template might have:

<img src="{{picture.image.url}}" title="{{picture.image.title}}"/>
pcardune
could you update your example to include a "thumbnail" field, which would resize the image to the max of 100 X 100?
dotty
If you use http://code.google.com/p/sorl-thumbnail/ you don't need a separate thumbnail field - just use the {% thumbnail %} tag and a thumbnail is automatically generated for you the first time the template is rendered...{% thumbnail picture 100x100 %}
msanders