Login

Handling Image uploading and Delete Old Image in Django

Author:
mulianto
Posted:
May 18, 2012
Language:
Python
Version:
1.3
Tags:
image-uploading django-image-field-upload-with-auto-delete-old-image Django
Score:
0 (after 0 ratings)

The snipped will do : 1.accept image upload by a form 2.check the old image, if there delete it in media folder 3.after delete, save the image uploaded with slug name provided

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
"""
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) )

More like this

  1. Image uploader to use with file uploader from http://github.com/valums/file-uploader by tgdn 3 years, 4 months ago
  2. Add a "remove file" field for Image- or FileFields by rodrigoc 6 years, 10 months ago
  3. Unzip a .zip file uploaded with FileBrowser by shacker 5 years, 3 months ago
  4. A Django form field that accepts an uploaded image and creates a resized image attached with a push-pin by rmisio 3 years, 12 months ago
  5. Signal to resize uploaded Fiber images as new thumbnailed images by versae 3 years, 3 months ago

Comments

Please login first before commenting.