""" 2-May-2012 Creator:Phang Mulianto Email:braveh4rt@gmail.com Image upload handling in django To save an uploaded images and rewrite the old image The image expected is .jpg The model is Thumbnail with fields : slug image created modified we name the image in the media with slug data The form created with imgUploadModelForm """ def upload_the_image(request): data = Thumbnail.objects.get(pk=id) if request.method == 'POST': # If the form has been submitted... form = imgUploadModelForm(request.POST,request.FILES,instance=data) # A form bound to the POST data if form.is_valid(): # All validation rules pass picture, created = Thumbnail.objects.get_or_create(pk=form.cleaned_data['id']) if not created: #there is already an image uploaded try: if picture.image.name:#if there is file name entry, delete it import os from django.conf import settings #we delete the previous image os.remove(os.path.join(settings.MEDIA_ROOT,str(picture.image.name) )) fp=form.save(commit=False) fp.Thumbnail.name=form.cleaned_data['slug']+'.jpg' fp.save() messages.success(request, me+' Image Uploaded ') except OSError: messages.error(request, me+' Upload Failed ') return render_to_response(template_name,locals(),context_instance = RequestContext(request) )