Login

Handling Image uploading and Delete Old Image in Django

Author:
mulianto
Posted:
May 18, 2012
Language:
Python
Version:
1.3
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:[email protected]

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. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.