Wednesday, March 25, 2015

Re: image handling

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

2015-03-25 9:32 GMT+01:00 Akash Patni <akash.patni@ranosys.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.

On Wed, Mar 25, 2015 at 1:44 PM, Andreas Kuhne <andreas.kuhne@suitopia.com> wrote:
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

2015-03-25 5:26 GMT+01:00 Akash Patni <akash.patni@ranosys.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.


On Wed, Mar 25, 2015 at 9:28 AM, Akash Patni <akash.patni@ranosys.com> wrote:
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


On Tue, Mar 24, 2015 at 7:44 PM, Andreas Kuhne <andreas.kuhne@suitopia.com> wrote:
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

2015-03-24 14:20 GMT+01:00 Akash Patni <akash.patni@ranosys.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
    
    


On Tue, Mar 24, 2015 at 6:47 PM, Akash Patni <akash.patni@ranosys.com> wrote:
is there any other changes that i have to made in model like how this above mentioned function will be call.

Please suggest 

On Tue, Mar 24, 2015 at 6:43 PM, Andreas Kuhne <andreas.kuhne@suitopia.com> wrote:
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

2015-03-24 14:10 GMT+01:00 Akash Patni <akash.patni@ranosys.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

On Tue, Mar 24, 2015 at 6:11 PM, Andreas Kuhne <andreas.kuhne@suitopia.com> wrote:
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

2015-03-24 11:40 GMT+01:00 <akash.patni@ranosys.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:
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@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/ca9fa002-cbd5-4bbf-b42c-2a6ce88e8e0c%40googlegroups.com.

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

--
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@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/CALXYUbkpM6op303LMxA2iGNuzqgzB%3DjBPWw2KXkpjwdaho2Z%2BQ%40mail.gmail.com.

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


--
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@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/CANSMZiTGE4rue_LtY3YrsERGqBuy%3DoFX0eJb_9o81R_us-OibQ%40mail.gmail.com.

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

--
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@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/CALXYUb%3DxUnSdyTevvw3oSwA%2B1kpvMwBXednRxkswXMUkMdU78g%40mail.gmail.com.

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





--
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


--
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@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/CANSMZiRtfvrhxmUrw-GM4dsbakkM7ccONbHDVA4y4NCywX3aFA%40mail.gmail.com.

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

--
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@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/CALXYUbmecLasSsdZkk_7-uOB_5N3PVqY0i4rhbhV2o_DcDf3aQ%40mail.gmail.com.

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





--
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


--
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@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/CANSMZiTwrGT%3D%2BqS6H6_qusp-oL9H0nSsQV0frOhRuqaJeZnHHg%40mail.gmail.com.

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

--
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@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/CALXYUbkv75Y-3hRqOpeGEUs1GOAVB4aFmEFEhhMx3cdvaZvWaw%40mail.gmail.com.

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


--
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@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/CANSMZiQedy7mEY5NSMc5Y1h9sBZXLme%2BBXEinSjhgnP9Gq3dEQ%40mail.gmail.com.

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

--
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@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/CALXYUbnb2Z9sUANyrJVR1T383GCsVvrLJy9g57OOSRG%3D-z_0FQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment