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?
You should consider using an ImageField in your model. For example in models.py you would have:
And in your views you would just have:
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:
so a template might have: