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