Example #1
0
class Frontal_images(models.Model):
    frontal_image = models.ImageField(blank=True,
                                      null=True,
                                      upload_to='images/frontal_images/')

    def save(self, *args, **kwargs):
        # Do extra stuff before saving

        # If new post, get the frontal_image and resize it on the fly

        img = Image.open(self.frontal_image)
        output = BytesIO()

        img.save(output, format='JPEG', quality=40)
        output.seek(0)

        self.frontal_image = InMemoryUploadedFile(
            output, 'ImageField',
            "%s.jpg" % self.frontal_image.name.split('.')[0], 'image/jpeg',
            sys.getsizeof(output), None)

        super().save(*args, **kwargs)

    def __str__(self):
        return self.frontal_image.url

    def delete(self, *args, **kwargs):
        self.frontal_image.delete()
        super().delete(*args, **kwargs)
Example #2
0
class MyData(models.Model):
    class Meta(object):
        verbose_name = "Personal Data"

    name = models.CharField(
        validators=[validate_name_fields],
        max_length=30)
    last_name = models.CharField(
        validators=[validate_name_fields],
        max_length=30)
    birthday = models.DateField(validators=[validate_birthday])
    bio = models.TextField(
        max_length=256,
        blank=True,
        null=True)
    email = models.EmailField(
        max_length=30)
    jabber = models.EmailField(
        max_length=30)
    skype = models.CharField(
        max_length=30)
    other_conts = models.TextField(
        max_length=256,
        blank=True,
        null=True)
    photo = models.ImageField(
        blank=True,
        null=True,
        upload_to='img/')

    def save(self, *args, **kwargs):
        if self.photo:
            size = (200, 200)
            image = Image.open(StringIO.StringIO(self.photo.read()))
            (width, height) = image.size
            if (width > 200) or (height > 200):
                image.thumbnail(size, Image.ANTIALIAS)
            output = StringIO.StringIO()
            image.save(output, format='jpeg', quality=70)
            output.seek(0)
            self.photo = InMemoryUploadedFile(
                output,
                'ImageField', "%s.jpg" %
                              self.photo.name.split('.')[0],
                'image/jpeg', output.len, None)
        try:
            this = MyData.objects.get(id=self.id)
            if this.photo == self.photo:
                self.photo = this.photo
            else:
                this.photo.delete(save=False)
        except:
            pass
        super(MyData, self).save(*args, **kwargs)

    def __unicode__(self):
        return u"%s %s" % (self.name, self.last_name)
Example #3
0
class File(BaseModel):
    """Model for storing uploaded images.

    Uploaded images can be stored prior to creating Photo instance. This
    way you can upload images while user is typing other data.
    Images are checked if meet size and format requirements before
    saving.

    """

    class Meta:
        """File Meta options."""

        verbose_name = _('file')
        verbose_name_plural = _('files')

    #: uploaded file
    file = models.ImageField(upload_to=generate_file_filename)

    #: thumbnail of uploaded file
    thumbnail = models.ImageField(upload_to=generate_thumb_filename)

    def save(self, *args, **kwargs):  # pylint: disable=arguments-differ
        """Add photo thumbnail and save object."""
        if not self.pk:  # on create
            image = Image.open(self.file)
            image.thumbnail((100, 100), Image.ANTIALIAS)

            thumb = io.BytesIO()
            image.save(thumb, format="jpeg", quality=100, optimize=True, progressive=True)
            self.thumbnail = InMemoryUploadedFile(thumb, None, self.file.name, 'image/jpeg',
                                                  thumb.tell(), None)

        super(File, self).save(*args, **kwargs)

    def delete(self, *args, **kwargs):  # pylint: disable=arguments-differ
        """Delete attached images and actual object."""
        self.file.delete(save=False)  # pylint: disable=no-member
        self.thumbnail.delete(save=False)  # pylint: disable=no-member

        super(File, self).delete(*args, **kwargs)

    def get_long_edge(self):
        """Return longer edge of the image."""
        return max(self.file.width, self.file.height)  # pylint: disable=no-member

    def __str__(self):
        """Return string representation of File object."""
        photo = self.photo_set.first()  # pylint: disable=no-member
        photo_title = photo.title if photo else '?'
        photo_id = photo.pk if photo else '?'
        return "id: {}, filename: {}, photo id: {}, photo title: {}".format(
            self.pk, self.file.name, photo_id, photo_title)
Example #4
0
class Contacts(models.Model):
    name = models.CharField(max_length=25)
    lastname = models.CharField(max_length=25)
    email = models.EmailField()
    date_of_birth = models.DateField()
    jabber_id = models.CharField(max_length=25, null=True, blank=True)
    skype_login = models.CharField(max_length=25, null=True, blank=True)
    bio = models.TextField(max_length=300, null=True, blank=True)
    other_contacts = models.TextField(max_length=300, null=True, blank=True)
    image = models.ImageField(upload_to='images', blank=True, null=True)

    def __unicode__(self):
        return "%s %s's contacts" % (self.name, self.lastname)

    def save(self, *args, **kwargs):
        if self.image:
            image = Image.open(StringIO.StringIO(self.image.read()))
            image.thumbnail((200, 200), Image.ANTIALIAS)
            output = StringIO.StringIO()
            image.save(output, format='JPEG', quality=75)
            output.seek(0)

            name = self.image.name
            if 'jpeg' not in name:
                name = name[:name.rindex('.') + 1] + 'jpeg'
            self.image = InMemoryUploadedFile(output, 'ImageField',
                                              name, 'image/jpeg',
                                              output.len, None)

            # delete old image
            try:
                # we need to refresh object
                this = Contacts.objects.get(id=self.id)
                if this.image != self.image:
                    this.image.delete(False)
            except:
                pass

        super(Contacts, self).save(*args, **kwargs)
Example #5
0
class Document(
        models.Model, object
):  # all details comming about a particular picture uploaded                                                      #  get saved in this table
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    status = models.CharField(max_length=7, choices=choice1, default="PUBLIC")
    width = models.IntegerField(blank=True,
                                default=500,
                                help_text="Enter positive value ")
    height = models.IntegerField(blank=True,
                                 default=500,
                                 help_text="Enter positive value ")
    flip = models.CharField(max_length=17, choices=choice3, default="NONE")
    rotate = models.CharField(max_length=15, choices=choice4, default='NONE')
    blur = models.CharField(max_length=5, choices=choice5, default='n')
    effect = models.IntegerField(choices=choice6, default=1)
    document = models.ImageField(
        # upload_to=get_file_name
    )
    uploaded_at = models.DateTimeField(auto_now_add=True)

    like_or_not = models.IntegerField(default=0)
    like_user = models.ManyToManyField(User, related_name='hello', blank=True)

    def __str__(self):
        return self.user.username

    def __unicode__(self):  # gives a common name to objects
        return self.document

    def get_absolute_url(self):
        return reverse('model_form_upload', kwargs={'pk': self.pk})

    def save(self):
        im = Image.open(self.document)  #opens a particular image

        output = BytesIO()  #file is written into memory

        im = im.resize((self.width, self.height))
        if self.flip == 'horizon':
            im = im.transpose(Image.FLIP_LEFT_RIGHT)
        elif self.flip == 'vertical':
            im = im.transpose(Image.FLIP_TOP_BOTTOM)
        elif self.flip == 'NONE':
            pass

        if self.rotate == 'clock':
            im = im.rotate(270)
        elif self.rotate == 'anti':
            im = im.rotate(90)
        elif self.rotate == 'NONE':
            pass

        if self.blur == 'y':
            im = im.filter(ImageFilter.BLUR)
        elif self.blur == 'n':
            pass

        if self.effect == 1:
            im = im.convert('RGB')
            r, g, b = im.split()
            im = Image.merge('RGB', (r, g, b))
        elif self.effect == 2:
            im = im.convert('RGB')
            r, g, b = im.split()
            im = Image.merge('RGB', (b, g, r))
        elif self.effect == 3:
            im = im.convert('RGB')
            r, g, b = im.split()
            im = Image.merge('RGB', (g, r, b))
        elif self.effect == 4:
            width, height = im.size
            for i in range(width):
                for j in range(height):
                    r, g, b = im.getpixel((i, j))
                    c = int(round((r + g + b) / 3))
                    im.putpixel((i, j), (c, c, c))
        elif self.effect == 5:
            im = im.convert('RGB')
            r, g, b = im.split()
            im = Image.merge('RGB', (r, b, g))
        elif self.effect == 6:
            im = im.filter(ImageFilter.FIND_EDGES)
        elif self.effect == 7:
            im = ImageOps.invert(im)
        elif self.effect == 8:
            width, height = im.size
            for i in range(width):
                for j in range(height):
                    r, g, b = im.getpixel((i, j))
                    c = int((round(r + g + b) / 3))
                    R, G, B = c + 100, c + 100, c
                    im.putpixel((i, j), (R, G, B))
        im.save(output, format='JPEG',
                quality=100)  # saving the image into the file in memory

        # self.document = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.document.name.split('.')[0],
        #                                      'image/jpeg', sys.getsizeof(output), None)
        self.document = InMemoryUploadedFile(
            output, None, "%s.jpg" % self.document.name.split('.')[0],
            'image/jpeg', sys.getsizeof(output), None)

        temp_name = self.document.name
        try:
            this = Document.objects.get(id=self.id)
            if this.document == self.document:
                self.document = this.document
            else:
                this.document.delete(save=False)
        except:
            pass  # when new image

        self.document.save(temp_name,
                           content=ContentFile(output.getvalue()),
                           save=False)
        print(self.document)
        super(Document, self).save(force_insert=False, )
Example #6
0
class Person(models.Model):
    first_name = models.CharField("name", max_length=30)
    last_name = models.CharField("last name", max_length=30)
    date_of_birthday = models.DateField(
        "date of birth",
        help_text="Please use the following format: <em>YYYY-MM-DD</em>.")
    bio = models.TextField("bio", max_length=255, blank=True)
    email = models.EmailField("email")
    jabber = models.CharField("jabber",
                              max_length=30, blank=True)
    skype = models.CharField("skype",
                             max_length=30, blank=True)
    other_contacts = models.TextField("other contacts",
                                      max_length=255, blank=True)

    person_pic = models.ImageField("photo",
                                   upload_to='pic_folder/',
                                   default='',
                                   blank=True)

    def __unicode__(self):
        return "%s %s %s" % (self.first_name, self.last_name, self.email)

    def save(self, *args, **kwargs):
        image_width = 200
        image_height = 200
        image_size = (image_width, image_height)
        image_isSame = False

        if self.person_pic:
            try:
                this = Person.objects.get(id=self.id)
                if this.person_pic == self.person_pic:
                    image_isSame = True
            except:
                pass

            image = Img.open(StringIO.StringIO(self.person_pic.read()))

            if image.mode not in ("L", "RGB"):
                image = image.convert("RGB")

            (imw, imh) = image.size
            if (imw > image_width) or (imh > image_height):
                image.thumbnail(image_size, Img.ANTIALIAS)

            output = StringIO.StringIO()
            image.save(output, format='JPEG', quality=75)
            output.seek(0)
            self.person_pic = InMemoryUploadedFile(
                output,
                'ImageField',
                "%s.jpg" % self.person_pic.name.split('.')[0],
                'image/jpeg', output.len, None
            )

        try:
            this = Person.objects.get(id=self.id)
            if this.person_pic == self.person_pic or image_isSame:
                self.person_pic = this.person_pic
            else:
                this.person_pic.delete(save=False)
        except:
            pass

        super(Person, self).save(*args, **kwargs)

    class Meta:
        verbose_name = 'Person'
        verbose_name_plural = 'People'
Example #7
0
class Partners(OrderedModel, TranslatableModel, SubDomainMixin, UUIDMixin, TimeStampMixin, ClassMethodMixin):
    link = models.CharField(
        verbose_name=_('MODEL_PARTNERS_LINK_NAME'),
        max_length=150)

    logotip = models.ImageField(
        verbose_name=_('MODEL_PARTNERS_LOGOTIP_NAME'),
        upload_to=uploaded_filepath)

    group = models.ForeignKey(
        PartnerGroups,
        verbose_name=_('MODEL_PARTNERS_GROUP_NAME'),
        related_name='partners',
        related_query_name='partner')

    translations = TranslatedFields(
        title=models.CharField(
            verbose_name=_('MODEL_PARTNERS_TITLE_NAME'),
            max_length=100),

        description=models.TextField(
            _('MODEL_PARTNERS_DESCRIPTION_NAME'),
            blank=True,
            null=True),
    )

    class Meta(OrderedModel.Meta):
        db_table = 'data_partners'
        verbose_name = _('MODEL_PARTNER_NAME')
        verbose_name_plural = _('MODEL_PARTNERS_NAME')

    def get_title(self):
        return self.lazy_translation_getter('title')

    def get_group(self):
        return self.group.get_title()

    def get_description(self):
        return self.lazy_translation_getter('description')

    def __str__(self):
        return self.get_title()

    def get_logotip_url(self):
        return self.logotip.url

    def get_subdomain(self):
        return self.subdomain.slug

    def save(self, *args, **kwargs):
        width = 180
        height = 180
        size = (width, height)
        isSame = False

        if self.logotip:
            try:
                this = Partners.objects.get(id=self.id)
                if this.logotip == self.logotip:
                    isSame = True
            except:
                pass

            image = Image.open(self.logotip)
            (imw, imh) = image.size

            if (imw > width) or (imh > height):
                image.thumbnail(size, Image.ANTIALIAS)

            if image.mode == 'RGBA':
                image.load()
                background = Image.new('RGB', image.size, (255, 255, 255))
                background.paste(image, mask=image.split()[3])
                image = background

            output = BytesIO()
            image.save(output, format='JPEG', quality=80)
            output.seek(0)

            self.logotip = InMemoryUploadedFile(
                output, 'ImageField', '%s.jpg' % self.logotip.name.split('.')[0], 'image/jpeg', output.getvalue(), None)

        try:
            this = Partners.objects.get(id=self.id)
            if this.logotip == self.logotip or isSame:
                self.logotip = this.logotip
            else:
                this.logotip.delete(save=False)
        except:
            pass

        super(Partners, self).save(*args, **kwargs)