image handling

53 views
Skip to first unread message

akash...@ranosys.com

unread,
Mar 24, 2015, 5:10:35 AM3/24/15
to django...@googlegroups.com
hi..
Can anyone please tell me how to handle old image after uploading new image.

Andreas Kuhne

unread,
Mar 24, 2015, 5:35:46 AM3/24/15
to django...@googlegroups.com
Hi,

I think you'll have to be more specific, what do you want to do with the old image? Delete it? Use it again?

Regards,

Andréas

2015-03-24 10:08 GMT+01:00 <akash...@ranosys.com>:
hi..
Can anyone please tell me how to handle old image after uploading new image.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/83341a1f-5684-4aad-8f87-268f25f15adb%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

akash...@ranosys.com

unread,
Mar 24, 2015, 5:59:46 AM3/24/15
to django...@googlegroups.com
Hi ,
I want to delete the old image.

akash...@ranosys.com

unread,
Mar 24, 2015, 6:04:01 AM3/24/15
to django...@googlegroups.com
This is my model
class User(models.Model):
    first_name=models.CharField(verbose_name = "First Name *",max_length=20,blank=False)
    last_name=models.CharField(verbose_name = "Last Name *",max_length=20,blank=False)
    username=models.EmailField(verbose_name = "Email *",max_length=30,blank=False)
    password=models.CharField(verbose_name = "Password *",max_length=15,blank=False)
    dob=models.DateField(verbose_name = "DOB *" ,blank=True,null=True)
    mobileno=models.CharField(verbose_name = "Mobile No *",max_length=20,blank=False)
    houseno=models.CharField(verbose_name = "House No",max_length=10,blank=True)
    address1=models.CharField(verbose_name = "Adress1",max_length=30,blank=True)
    city=models.CharField(verbose_name = "City",max_length=20,blank=True)
    state=models.CharField(verbose_name = "State",max_length=30,blank=True)
    pincode=models.CharField(verbose_name = "Pincode",max_length=20,blank=True)
    country=models.CharField(verbose_name = "Country",max_length=30,blank=True)
    comment=models.CharField(verbose_name = "Comment",max_length=200,blank=True)
    sex=models.CharField(verbose_name = "Sex *",max_length=5,blank=False)
    image=models.FileField(verbose_name = "Image(limit 1Mb) *",blank=True,upload_to='media/')
   
    def __unicode__(self):
        return self.first_name


this is my form
class Registration(forms.ModelForm):
      password = forms.CharField(label='Password *',widget=forms.PasswordInput())
      image = forms.ImageField(label='Select a file *',help_text='max. 1 megabytes')
      class Meta:

view.py
def registration(request):
    #request.session.set_test_cookie()
    if request.method == "POST":
            regform=Registration(request.POST,request.FILES)
            if regform.is_valid():
               #item=resize_and_crop(img_path, modified_path, size, crop_type='top')
               regform.save();
               return HttpResponseRedirect('/login/')
               
            else:
                return render_to_response('registration.html',{"form":regform})
    else:
        regform=Registration()
    return render_to_response('registration.html',{"form":regform})


can anyone please tell how to handle this means how to delete the old image

Please...

akash...@ranosys.com

unread,
Mar 24, 2015, 6:08:07 AM3/24/15
to django...@googlegroups.com
This is my edit profile function in view

def edit_profile(request):     
    if 'username' in request.session:
        user_id=request.POST.get('id')
        user_id=request.GET.get('id')
        usr_obj=User.objects.get(id=int(user_id))
        if request.method=="POST":
                regform=Registration(instance=usr_obj,data = request.POST)
                if regform.is_valid():
                    regform.save();
                    return HttpResponseRedirect('/index/')
                else:
                    return render_to_response("edit_profile.html",{"form":regform,})
        else:      
            user_id=request.GET.get('id')
            usr_obj=User.objects.get(id=int(user_id))
     #temp_data={'first_name':user_id.first_name,'last_name':user_id.last_name,'email':user_id.email,'password':user_id.password,'dob':user_id.dob,'mobileno':user_id.mobileno,'houseno':user_id.houseno,'address1':user_id.address1,'city':user_id.city,'state':user_id.state,'pincode':user_id.pincode,'country':user_id.country,'comment':user_id.comment,'sex':user_id.sex}
            regform=Registration(instance=usr_obj)
            return render_to_response("edit_profile.html",{"form":regform,"user_id":user_id})


akash...@ranosys.com

unread,
Mar 24, 2015, 6:21:31 AM3/24/15
to django...@googlegroups.com
hieeeeeeee
any answer


On Tuesday, March 24, 2015 at 2:40:35 PM UTC+5:30, akash...@ranosys.com wrote:

aRkadeFR

unread,
Mar 24, 2015, 6:31:44 AM3/24/15
to django...@googlegroups.com
When do you want to delete the old image?
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.

akash...@ranosys.com

unread,
Mar 24, 2015, 6:40:18 AM3/24/15
to django...@googlegroups.com
When i edit image that is when i upload new image,the old image should get deleted


On Tuesday, March 24, 2015 at 2:40:35 PM UTC+5:30, akash...@ranosys.com wrote:

Andreas Kuhne

unread,
Mar 24, 2015, 8:41:48 AM3/24/15
to django...@googlegroups.com
Hi,

Ok, so what you should do is add a signal to pre save and then delete the old image if the new image is attached.

Something like this should work:

from django.core.files.storage import default_storage as storage
from django.db.models.signals import pre_save


def image_delete(sender, instance, *args, **kwargs):
    old_instance = User.objects.get(pk=instance.pk)
    
    if old_instance.image != instance.image and instance.image:
      storage.delete(old_instance.image.name)

pre_save.connect(image_delete, sender=User)

You can see more information about signals here: https://docs.djangoproject.com/en/1.7/topics/signals/

Regards,

Andréas

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.

Akash Patni

unread,
Mar 24, 2015, 9:10:43 AM3/24/15
to django...@googlegroups.com
Hey,
I am new to django. I have other feilds also other than image field in my form, so will you please tell me how to use above mentioned function in edit_profile function in view, Can i call another function from another function in views.py, if yes please tell me

--
You received this message because you are subscribed to a topic in the Google Groups "Django users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-users/oZrAdWgzwo0/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-users...@googlegroups.com.

To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.

For more options, visit https://groups.google.com/d/optout.



--
Best Regards,
Akash Patni
Software Engineer

ranosys
  facebooktwitterlinkedingoogleplus 

Head Office: 
Oxley Bizhub, #06-48 | 73 Ubi Road 1 | Singapore - 408733
Tel: +65 66331556  |  HP: +65 98573420

Global Offices:
San Francisco, USA | Jaipur, India | Bikaner, India


Andreas Kuhne

unread,
Mar 24, 2015, 9:13:58 AM3/24/15
to django...@googlegroups.com
Hi, 

You shouldn't do it in the view, do it in the database model instead. It won't do anything to any other fields than the image field the way I wrote the function (all other fields are untouched). 

The reason you shouldn't do it in the view, is because if you were to update the image any other place than via the view, the code wouldn't run. It's more sensible and more DRY to do it in the model.

Regards,

Andréas

Akash Patni

unread,
Mar 24, 2015, 9:18:10 AM3/24/15
to django...@googlegroups.com
is there any other changes that i have to made in model like how this above mentioned function will be call.

Please suggest 


For more options, visit https://groups.google.com/d/optout.

Akash Patni

unread,
Mar 24, 2015, 9:20:52 AM3/24/15
to django...@googlegroups.com
i had made the changes in model .py but its not working

here is model.py


from django.db import models
import django.forms as forms
from virtualenv import REQUIRED_FILES
from _mysql import NULL
from datetime import datetime, date, time, timedelta
import time
import calendar
from django.contrib.auth.models import User
import os
from uuid import uuid4
from django.core.files.storage import default_storage as storage
from django.db.models.signals import pre_save


def path_and_rename(path):
    def wrapper(instance, filename):
        ext = filename.split('.')[-1]
        # get filename
        if instance.pk:
            filename = '{}.{}'.format(instance.pk, ext)
        else:
            # set filename as random string
            filename = '{}.{}'.format(uuid4().hex, ext)
        # return the whole path to the file
        return os.path.join(path, filename)
    return wrapper

def image_delete(sender, instance, *args, **kwargs):
    old_instance = User.objects.get(pk=instance.pk)
    
    if old_instance.image != instance.image and instance.image:
      storage.delete(old_instance.image.name)

pre_save.connect(image_delete, sender=User)

class Publisher(models.Model):
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=50)
    city = models.CharField(max_length=60)
    state_province = models.CharField(max_length=30)
    country = models.CharField(max_length=50)
    website = models.URLField()
    
    def __unicode__(self):
        return self.name
    
class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()
    
    def __unicode__(self):
        return u'%s %s' % (self.first_name, self.last_name)

class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()
    
    def __unicode__(self):
        return self.title
    
class User(models.Model):
    first_name=models.CharField(verbose_name = "First Name *",max_length=20,blank=False)
    last_name=models.CharField(verbose_name = "Last Name *",max_length=20,blank=False)
    username=models.EmailField(verbose_name = "Email *",max_length=30,blank=False)
    password=models.CharField(verbose_name = "Password *",max_length=15,blank=False)
    dob=models.DateField(verbose_name = "DOB *" ,blank=True,null=True)
    mobileno=models.CharField(verbose_name = "Mobile No *",max_length=20,blank=False)
    houseno=models.CharField(verbose_name = "House No",max_length=10,blank=True)
    address1=models.CharField(verbose_name = "Adress1",max_length=30,blank=True)
    city=models.CharField(verbose_name = "City",max_length=20,blank=True)
    state=models.CharField(verbose_name = "State",max_length=30,blank=True)
    pincode=models.CharField(verbose_name = "Pincode",max_length=20,blank=True)
    country=models.CharField(verbose_name = "Country",max_length=30,blank=True)
    comment=models.CharField(verbose_name = "Comment",max_length=200,blank=True)
    sex=models.CharField(verbose_name = "Sex *",max_length=5,blank=False)
    image=models.FileField(verbose_name = "Image(limit 1Mb) *",blank=True,upload_to=path_and_rename(''))
    
    def __unicode__(self):
        return self.first_name
    
    

Andreas Kuhne

unread,
Mar 24, 2015, 10:15:32 AM3/24/15
to django...@googlegroups.com
First, make sure that the whitespace is the same in all of your methods (in python whitespace is significant, which means that you should indent all files the same amount, I wrote my example in my email, so I only indented twice, you seem to have 4 blankspaces in your file, so make sure the indentation is the same).

Secondly, I think that you should add the code I sent to the __init__.py file in the project itself (in the same directory that you have you models.py). That way it will be run during startup (which needs to be done).

Regards,

Andréas

Akash Patni

unread,
Mar 24, 2015, 11:59:32 PM3/24/15
to django...@googlegroups.com
Hi,
I have added the code to my  __init__.py file but still its not working.

__init__.py
from django.core.files.storage import default_storage as storage
from django.db.models.signals import pre_save
from django.db import models
import django.forms as forms
from django.contrib.auth.models import User

def image_delete(sender, instance, *args, **kwargs):
    old_instance = User.objects.get(pk=instance.pk)
    
    if old_instance.image != instance.image and instance.image:
      storage.delete(old_instance.image.name)
      pre_save.connect(image_delete, sender=User)

model.py

class User(models.Model):
    first_name=models.CharField(verbose_name = "First Name *",max_length=20,blank=False)
    last_name=models.CharField(verbose_name = "Last Name *",max_length=20,blank=False)
    username=models.EmailField(verbose_name = "Email *",max_length=30,blank=False)
    password=models.CharField(verbose_name = "Password *",max_length=15,blank=False)
    dob=models.DateField(verbose_name = "DOB *" ,blank=True,null=True)
    mobileno=models.CharField(verbose_name = "Mobile No *",max_length=20,blank=False)
    houseno=models.CharField(verbose_name = "House No",max_length=10,blank=True)
    address1=models.CharField(verbose_name = "Adress1",max_length=30,blank=True)
    city=models.CharField(verbose_name = "City",max_length=20,blank=True)
    state=models.CharField(verbose_name = "State",max_length=30,blank=True)
    pincode=models.CharField(verbose_name = "Pincode",max_length=20,blank=True)
    country=models.CharField(verbose_name = "Country",max_length=30,blank=True)
    comment=models.CharField(verbose_name = "Comment",max_length=200,blank=True)
    sex=models.CharField(verbose_name = "Sex *",max_length=5,blank=False)
    image=models.FileField(verbose_name = "Image(limit 1Mb) *",blank=True,upload_to=path_and_rename(''))
    
    def __unicode__(self):
        return self.first_name


For more options, visit https://groups.google.com/d/optout.

Akash Patni

unread,
Mar 25, 2015, 12:26:57 AM3/25/15
to django...@googlegroups.com
Hi,
Can i use this method in my model.py

def save(self, *args, **kwargs):
    try:
        this = MyModelName.objects.get(id=self.id)
        if this.MyImageFieldName != self.MyImageFieldName:
            this.MyImageFieldName.delete()
    except: pass
    super(MyModelName, self).save(*args, **kwargs)

class User(models.Model):
      image=models.FileField(verbose_name = "Image(limit 1Mb) *",blank=True,upload_to=path_and_rename(''),storage=save('self'))
      def __unicode__(self):
        return self.first_name
    i have doubt about storage in my file field which i have highlighted. Is it right, Please sugges.

Andreas Kuhne

unread,
Mar 25, 2015, 4:14:47 AM3/25/15
to django...@googlegroups.com
Hi,

No, that is not correct. The storage parameter has nothing to do with this. Also, why are you not using an ImageField instead of the FileField? Also you have to put all methods with "self" as a parameter with the class itself. Self is a pointer to the instance of the class, so it needs to be within the class.

You should do it this way:

class User:
    image = models.ImageField(verbose_name="Image (limit 1Mb) *", blank=True, upload_to='var/user/images')
    
    def save(self, *args, **kwargs):
        try:
            original_image = User.objects.get(id=self.id)
            if original_image.image != self.image:
                original_image.image.delete()
        except:
            pass
        super(User, self).save(*args, **kwargs)

Of course the other parts of the user object needs to be added as well. As you can see, I have also set a path for upload_to instead of a function, because using a function is only necessary when you want to set a unique path for each image (for example using the id for it). 

Regards,

Andréas

Akash Patni

unread,
Mar 25, 2015, 4:33:24 AM3/25/15
to django...@googlegroups.com
Hi..
ok will not give storage parameter, but how the function save will called.Will it be called automatically when i edit image.

I have used upload function to call a function which change the name of the image and save it to the database.


For more options, visit https://groups.google.com/d/optout.

Andreas Kuhne

unread,
Mar 25, 2015, 7:33:22 AM3/25/15
to django...@googlegroups.com
Hi again,

When you add the save function to a class, it overrides the builtin function that comes with the django db model. So it will be called everytime you call save on your model (which is called when you create or resave your model). Your form is a modelform, and somewhere in the code you should have:
class Meta:
model = User
This tells django that the form is created from the model. When you then save the form, it automatically saves the model instance (i.e. your User object), and then calls the save function. See: https://docs.djangoproject.com/en/1.7/topics/forms/modelforms/ and https://docs.djangoproject.com/en/1.7/topics/db/ . If you look at the documentation it will tell you how this should all be connected together.

Regards,

Andréas

Reply all
Reply to author
Forward
0 new messages