예제 #1
0
파일: models.py 프로젝트: teena22/imaginit
class UploadFile(models.Model):
    """Uploadfile and save."""

    file = ProcessedImageField(upload_to='profile/%Y/%m/%d',
                               processors=[ResizeToFit(800, 600, False)],
                               format='JPEG',
                               options={'quality': 100})
    owner = models.ForeignKey(User)
    edited = models.SmallIntegerField(default=0)
    created_on = models.DateTimeField(auto_now_add=True)
    modified_on = models.DateTimeField(auto_now=True)
    thumbnail = ImageSpecField(source='file',
                               processors=[ResizeToFit(200, 150, False)],
                               format='JPEG',
                               options={'quality': 100})

    class Meta:
        ordering = ('-modified_on', )

    def get_url(self):
        """
            Handle IOERR : This function checks if file exists,
            if it doesnt it deletes the record plus any thumbnail 
            that might exist
        """
        try:
            # get url if exists

            if os.path.isfile(BASE_DIR + self.file.url):
                return self.thumbnail.url
            # if the path is not a file do house cleaning
            self.delete()
            return None
        except IOError:
            return None
예제 #2
0
파일: models.py 프로젝트: slonidet/avcsite
class History(models.Model):
    photo = ProcessedImageField(
        upload_to='history/',
        processors=[ResizeToFit(600, 400, anchor=Anchor.CENTER)],
        format='JPEG',
        options={'quality': 100},
        verbose_name=u'Фото')
    thumb = ImageSpecField(
        source='photo',
        processors=[ResizeToFill(300, 200, anchor=Anchor.CENTER)],
        format='JPEG',
        options={'quality': 90})
    home_thumb = ImageSpecField(
        source='photo',
        processors=[ResizeToFit(200, 150, anchor=Anchor.CENTER)],
        format='JPEG',
        options={'quality': 90})
    name = models.CharField(max_length=90, verbose_name=u'Имя')
    fam = models.CharField(max_length=100, verbose_name=u'Фамилия', blank=True)
    desc = models.CharField(max_length=300,
                            verbose_name=u'Вид деятельности',
                            blank=True)
    date = models.DateField(verbose_name="Дата", default=datetime.date.today)
    quote = models.TextField(verbose_name="Цитата", blank=True)
    text = RichTextField(verbose_name=u'История', blank=True)

    def __unicode__(self):
        return self.name + " " + self.fam

    class Meta:
        verbose_name = u"История успеха"
        verbose_name_plural = u"Истории успеха"
예제 #3
0
파일: models.py 프로젝트: rpisarev/abi
class PortfImage(models.Model):
    def get_file_path(self, filename):
        extension = filename.split('.')[-1]
        filename = '%s.%s' % (uuid.uuid4(), extension)
        return os.path.join('images', filename)

    record = models.ForeignKey(PortfRecord, related_name='images', blank=True)
    image = models.ImageField(upload_to=get_file_path, max_length=256)
    name = models.CharField(max_length=60)
    image_small = ImageSpecField(
        [Adjust(contrast=1.2, sharpness=1.1),
         ResizeToFill(120, 120)],
        image_field='image',
        format='JPEG',
        options={'quality': 90})
    image_medium = ImageSpecField(
        [Adjust(contrast=1.2, sharpness=1.1),
         ResizeToFit(260, 260)],
        image_field='image',
        format='JPEG',
        options={'quality': 90})
    image_big = ImageSpecField(
        [Adjust(contrast=1.2, sharpness=1.1),
         ResizeToFit(640, 480)],
        image_field='image',
        format='JPEG',
        options={'quality': 90})
    '''image(s) to portfolio'''

    def __unicode__(self):
        return self.name
예제 #4
0
class Result(models.Model):
    """
    画風変換による出力画像'1枚'を保持する
    """
    material = models.ForeignKey(Material,
                                 related_name='results',
                                 on_delete=models.CASCADE)
    result_image = models.ImageField(upload_to='images/result/')
    result_image_xs = ImageSpecField(source='result_image',
                                     processors=[ResizeToFit(width='150')],
                                     format='JPEG',
                                     options={"quality": 60})
    result_image_sm = ImageSpecField(
        source='result_image',
        processors=[ResizeToFit(width='300', upscale=False)],
        format='JPEG',
    )

    iteration = models.IntegerField()
    result_info = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    result_name = models.CharField(
        blank=True, max_length=70)  # 作品名(is_public=Trueの時は必須となる)
    is_public = models.BooleanField(default=False)  # 共有するかどうか

    def __repr__(self):
        # 主キーとカウント数を返して見やすくする
        # ex: 1 : iteration()
        return "{}: iteration({:5d})".format(self.pk, self.iteration)

    __str__ = __repr__
예제 #5
0
파일: models.py 프로젝트: xncbf/jin-o-blog
class ImageInfo(models.Model):
    origin_image = models.ImageField('원본이미지')
    # resized_image = models.ImageField('리사이징', editable=False)
    resized_image = ImageSpecField(
        source='origin_image',
        processors=[ResizeToFit(1920, 1281, mat_color=(255, 255, 255))],
        options={'quality': 100},
    )
    # thumbnail_image = models.ImageField('썸네일', editable=False)
    thumbnail_image = ImageSpecField(
        source='origin_image',
        processors=[ResizeToFit(215, 143, mat_color=(255, 255, 255))],
        options={'quality': 95},
    )
    title = models.CharField('제목', max_length=500)
    detail = models.CharField('내용', max_length=500, blank=True)

    class Meta:
        verbose_name = "이미지"

    def save(self, *args, **kwargs):
        # if self.origin_image:
        # self.origin_image = get_thumbnail(self.image, '1920x1281', qualit
        # self.resized_image = self._resized_image
        # self.thumbnail_image = self._thumbnail_image
        super(ImageInfo, self).save(*args, **kwargs)
예제 #6
0
파일: models.py 프로젝트: fadich/nphoto2
class Photo(models.Model):
    original = models.ImageField(upload_to='media')
    large = ImageSpecField(source='original',
                           processors=[ResizeToFit(1200, 1200)])
    medium = ImageSpecField(source='original',
                            processors=[ResizeToFit(720, 720)])
    small = ImageSpecField(source='original',
                           processors=[ResizeToFit(320, 320)],
                           options={'quality': 60})

    name = models.CharField(max_length=255, default='<Noname>')
    description = models.TextField(blank=True, null=True)

    @property
    def photo_name(self):
        name = os.path.basename(self.original.name)
        return name

    def thumb(self):
        return render_to_string('admin/thumb.html', {
            'image': self.small,
        })

    thumb.allow_tags = True

    def __str__(self):
        return self.name
예제 #7
0
파일: models.py 프로젝트: sokogfb/1source
class Section(OrderedModel):
    title = models.CharField(max_length=100, unique=True)
    slug = AutoSlugField(populate_from='title',
                         editable=False,
                         always_update=True,
                         unique=True)
    featured_text = RichTextField(help_text="Orange bar section of text")
    teaser_text = models.TextField(
        help_text="Text displayed when no subsections are selected",
        blank=True)
    image = models.ImageField(blank=True,
                              default=None,
                              upload_to='section',
                              help_text="Background image for section")
    image_web = ImageSpecField(source='image',
                               processors=[ResizeToFit(width=1024)],
                               format='JPEG',
                               options={'quality': 88})
    image_mobile = ImageSpecField(source='image',
                                  processors=[ResizeToFit(width=480)],
                                  format='JPEG',
                                  options={'quality': 84})

    class Meta(OrderedModel.Meta):
        pass

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return '/#' + self.slug
예제 #8
0
class Image(models.Model):
    file = models.ImageField('Datei')
    creator = models.ForeignKey('gestalten.Gestalt',
                                related_name='images',
                                on_delete=models.PROTECT)

    preview_api = ImageSpecField(
        source='file', processors=[Transpose(),
                                   SmartResize(250, 250)])
    preview_content = ImageSpecField(
        source='file', processors=[Transpose(),
                                   SmartResize(200, 200)])
    preview_gallery = ImageSpecField(
        source='file', processors=[Transpose(), ResizeToFit(250)])
    preview_group = ImageSpecField(
        source='file', processors=[Transpose(),
                                   SmartResize(366, 120)])
    intro = ImageSpecField(source='file',
                           processors=[Transpose(),
                                       ResizeToFit(554)])
    sidebar = ImageSpecField(source='file',
                             processors=[Transpose(),
                                         ResizeToFit(313)])
    facebook_meta = ImageSpecField(source='file',
                                   processors=[Transpose(),
                                               ResizeToFit(800)])
    twitter_meta = ImageSpecField(
        source='file', processors=[Transpose(),
                                   SmartResize(600, 300)])

    def __str__(self):
        return '{} ({})'.format(self.file, self.creator)[2:]
class Photo(models.Model):
    gallery = models.ForeignKey(to="Gallery",
                                on_delete=models.CASCADE,
                                related_name='photos')
    title = models.CharField(max_length=20)
    description = models.TextField(null=True, blank=True, max_length=100)
    alt_text = models.CharField(max_length=30)
    photo = models.ImageField(upload_to='media/gallery_photos/')
    photo_large = ImageSpecField(
        source='photo',
        processors=[ResizeToFit(600, 800, upscale=False)],
        format='JPEG',
        options={'quality': 65})
    photo_medium = ImageSpecField(
        source='photo',
        processors=[ResizeToFit(450, 600, upscale=False)],
        format='JPEG',
        options={'quality': 65})
    photo_thumbnail = ImageSpecField(source='photo',
                                     processors=[ResizeToFill(200, 200)],
                                     format='JPEG',
                                     options={'quality': 65})
    default = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    commenting_users = models.ManyToManyField(User, through='Comment')

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['gallery'],
                                    condition=models.Q(default=True),
                                    name='unique_default_photo')
        ]
예제 #10
0
class AlbumImage(models.Model):
    class Meta(object):
        verbose_name = u"Фотография"
        verbose_name_plural = u"Фотографии"
        ordering = ('-created', )

    image = ProcessedImageField(upload_to='albums',
                                processors=[ResizeToFit(1280)],
                                format='JPEG',
                                options={'quality': 70},
                                verbose_name=u'Изображение')
    image_300 = ProcessedImageField(upload_to='albums',
                                    processors=[ResizeToFit(300)],
                                    format='JPEG',
                                    options={'quality': 80},
                                    verbose_name=u'Фото 300')
    image_100 = ProcessedImageField(upload_to='albums',
                                    processors=[ResizeToFit(100)],
                                    format='JPEG',
                                    options={'quality': 90},
                                    verbose_name=u'Фото 100')
    album = models.ForeignKey(Album,
                              on_delete=models.CASCADE,
                              verbose_name=u'Альбом')
    created = models.DateTimeField(auto_now_add=True,
                                   verbose_name=u'Дата создания')
    width = models.IntegerField(default=0, verbose_name=u'Ширина')
    height = models.IntegerField(default=0, verbose_name=u'Высота')
    slug = models.SlugField(max_length=70, default=uuid.uuid4, editable=False)
예제 #11
0
class ProformaConfiguracion(models.Model):
    def firma_upload_to(instance, filename):
        fecha = timezone.datetime.now()
        return "proforma/configuracion/firma_%s%s%s%s%s%s.%s" % (
            fecha.year, fecha.month, fecha.day, fecha.hour, fecha.minute,
            fecha.second, filename.split('.')[-1])

    def encabezado_upload_to(instance, filename):
        fecha = timezone.datetime.now()
        return "proforma/configuracion/encabezado_%s%s%s%s%s%s.%s" % (
            fecha.year, fecha.month, fecha.day, fecha.hour, fecha.minute,
            fecha.second, filename.split('.')[-1])

    informacion_odecopack = models.TextField(null=True)
    informacion_bancaria = models.TextField(null=True)
    firma = ProcessedImageField(
        processors=[ResizeToFit(width=400, height=300, upscale=False)],
        format='PNG',
        options={'quality': 100},
        null=True,
        upload_to=firma_upload_to)
    encabezado = ProcessedImageField(processors=[ResizeToFit(1190, 228)],
                                     format='PNG',
                                     options={'quality': 100},
                                     null=True,
                                     upload_to=encabezado_upload_to)
예제 #12
0
class Picture(models.Model):
    title = models.CharField(max_length=255)
    photo = models.ImageField(upload_to='photo_photos/', null=True, blank=True)
    photo_thumbnail = ImageSpecField(
        source="photo",
        processors=[ResizeToFill(200, 200)],
        format="JPEG",
        options={"quality": 60},
        )
    photo_medium = ImageSpecField(
        source="photo",
        processors=[ResizeToFit(300, 300)],
        format="JPEG",
        options={"quality": 90},
        )
    photo_large = ImageSpecField(
        source="photo",
        processors=[ResizeToFit(800, 800)],
        format="JPEG",
        options={"quality": 100},
        )
    uploaded_date = models.DateTimeField(auto_now_add=True)
    public = models.BooleanField(default=False)
    owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='photos')
    albums = models.ManyToManyField(Album, related_name='photos', blank=True)

    class Meta:
        ordering = ['uploaded_date']

    def __str__(self):
        return f'{self.title} by {self.owner.username}'
예제 #13
0
class Posting(models.Model):

    content = models.TextField(default='')
    icon = models.CharField(max_length=20, default='')
    # save as origin
    # image = models.ImageField(blank=True,upload_to='postings/%Y%m%d')

    # Resize
    image = ProcessedImageField(
        blank=True,
        upload_to='postings/resize/%Y%m%d',
        processors=[ResizeToFit(width=960, upscale=False)],
        format='JPEG'
    )
    image_thumbnail = ImageSpecField(
        source='image',
        processors=[ResizeToFit(width=320, upscale=False)],
        format='JPEG',
        options={'quality':60}
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f'{self.id}: {self.content[:20]}'

    def save(self, *args, **kwargs):
         super().save(*args,**kwargs)
         print(f'\n=== Saved Posting with id:{self.id} ===')
         print(f'    content:{self.content}')
         if self.image:
             print(f'    image:{self.image.width}px * {self.image.height}px: {round(self.image.size/1024)}kb')
         print('================================\n')
예제 #14
0
파일: models.py 프로젝트: Afectus/crm_dev
class materialvalue(models.Model):
	id = models.AutoField(primary_key=True, unique=True)
	category = models.CharField(verbose_name='Категория', max_length=300, choices=CATEGORY, default='e')
	name = models.CharField(verbose_name='Название', max_length=255)
	model = models.CharField(verbose_name='Модель', max_length=255, blank=True)
	serial = models.CharField(verbose_name='Серийный номер', max_length=255, blank=True)
	pictdesc = models.ImageField(verbose_name='Фото наклейки/шильдика/штрихкода', upload_to=make_upload_path, max_length=500, blank=True, null=True)
	pictdesc200 = ImageSpecField(source='pictdesc', processors=[ResizeToFit(200, 200)], format='PNG', options={'quality': 95})
	photo = models.ImageField(verbose_name='Фото объекта', upload_to=make_upload_path, max_length=500, blank=True, null=True)
	photo200 = ImageSpecField(source='photo', processors=[ResizeToFit(200, 200)], format='PNG', options={'quality': 75})
	photo100 = ImageSpecField(source='photo', processors=[ResizeToFit(100, 100)], format='PNG', options={'quality': 75})
	photo500 = ImageSpecField(source='photo', processors=[ResizeToFit(500, 500)], format='PNG', options={'quality': 75})
	photo800 = ImageSpecField(source='photo', processors=[ResizeToFit(800, 800)], format='PNG', options={'quality': 75})
	status = models.CharField(verbose_name='Статус', max_length=30, choices=MLIST, default='inuse')
	amount = models.IntegerField(verbose_name='Количество', default=1)
	assessed_value = models.FloatField(verbose_name='Оценочная стоимость', default=0, blank=True, null=True)
	parent = models.ForeignKey('self', verbose_name='Связать с ценностью', on_delete=models.SET_NULL, null=True, blank=True)

	def __str__(self):
		return u'%s %s' % (self.id, self.name)

	class Meta:
		ordering=['-id']
		verbose_name = u'Материальные ценности'
		verbose_name_plural = u'Материальные ценности'
예제 #15
0
파일: models.py 프로젝트: Afectus/crm_dev
class imagebase(models.Model):
    id = models.AutoField(primary_key=True, unique=True, verbose_name='id')
    ctime = models.DateTimeField(verbose_name=u'Дата', auto_now_add=True)
    title = models.CharField(verbose_name=u'Заголовок',
                             help_text='Заголовок',
                             max_length=200)

    #pict
    pict = models.ImageField(verbose_name=u'Картинка',
                             upload_to=make_upload_path,
                             max_length=300)
    pict100 = ImageSpecField(source='pict',
                             processors=[ResizeToFit(100, 100)],
                             format='PNG',
                             options={'quality': 75})
    pict200 = ImageSpecField(source='pict',
                             processors=[ResizeToFit(200, 200)],
                             format='PNG',
                             options={'quality': 75})
    pict300 = ImageSpecField(source='pict',
                             processors=[ResizeToFit(300, 300)],
                             format='PNG',
                             options={'quality': 75})

    def __str__(self):
        return u'%s' % (self.id)

    class Meta:
        ordering = ['-id']
        verbose_name = u'База изображений'
        verbose_name_plural = u'База изображений'
예제 #16
0
class Site(models.Model):
    site_name = models.CharField(max_length=50)
    title = models.CharField(max_length=50)
    sub_title = models.CharField(max_length=75, blank=True)
    background = models.ImageField(upload_to='images/sites',
                                   null=True,
                                   blank=True)
    background_small = ImageSpecField(
        source='background',
        processors=[ResizeToFit(width=1440, upscale=False)],
        format='JPEG',
        options={'quality': 80})
    text1 = models.TextField(max_length=500, blank=True)
    text2 = models.TextField(max_length=500, blank=True)
    photo1 = models.ImageField(upload_to='images/sites', null=True, blank=True)
    photo1_thumb = ImageSpecField(
        source='photo1',
        processors=[ResizeToFit(width=200, upscale=False)],
        format='JPEG',
        options={'quality': 80})
    meta_title = models.CharField(max_length=100, blank=True)
    meta_description = models.CharField(max_length=200, blank=True)

    def __str__(self):
        return self.site_name
예제 #17
0
class Image(models.Model):
    SIZE_TYPES = (
            (1, '600x600'),
            (2, '700x700'),
            (3, '800x800'),
            (4, '900x900'),
            (5, '1000x1000'),
            )
    imag = models.ImageField(verbose_name='Изображение')

    size_type = models.IntegerField(verbose_name = 'Выберите размер для ресайза изображения', choices = SIZE_TYPES, default = '1') 
    imag_one =ImageSpecField([Adjust(contrast=1.2, sharpness=1.1),
            ResizeToFit(600,600)], source='imag', options={'quality': 90})
    imag_two =ImageSpecField([Adjust(contrast=1.2, sharpness=1.1),
            ResizeToFit(700, 700)], source='imag', options={'quality': 90})
    imag_three =ImageSpecField([Adjust(contrast=1.2, sharpness=1.1),
            ResizeToFit(800, 800)], source='imag',options={'quality': 90})
    imag_four =ImageSpecField([Adjust(contrast=1.2, sharpness=1.1),
            ResizeToFit(900, 900)], source='imag', options={'quality': 90})
    imag_five =ImageSpecField([Adjust(contrast=1.2, sharpness=1.1),
            ResizeToFit(1000, 1000)], source='imag', options={'quality': 90})


    User = get_user_model()
    user = models.ForeignKey(User, verbose_name='User', on_delete=models.CASCADE)

    
예제 #18
0
class PrintPhotoHeader(models.Model):
    title = models.CharField("Текст в заголовке",  max_length=1000, blank=True, null=True, default=None)
    image_header = models.ImageField("Картинка в заголовке", upload_to='photo_doc/',blank=True, null=True)
    image_header_hd= ImageSpecField(source = 'image_header',
                                            processors=[ResizeToFit(1920,400)],
                                            format='JPEG',
                                            options={'quality':90})
    image_header_notebook = ImageSpecField(source = 'image_header',
                                            processors=[ResizeToFit(1366, 400)],
                                            format='JPEG',
                                            options={'quality':90})

    image_header_medium = ImageSpecField(source = 'image_header',
                                            processors=[ResizeToFit(1280,400)],
                                            format='JPEG',
                                            options={'quality':90})
    image_header_smoll= ImageSpecField(source = 'image_header',
                                            processors=[ResizeToFit(768,)],
                                            format='JPEG',
                                            options={'quality':90})
    
    def __unicode__(self):
        return "%s   %s" % (self.title, self.image_header) 

    class Meta:
        verbose_name = 'Заголовок в Фото на документы'
        verbose_name_plural = 'Заголовоки в Фото на документы'
예제 #19
0
 def get_file_path(self, filename):
     extension = filename.split('.')[-1]
     filename = "%s.%s" % (uuid.uuid4(), extension)
     return os.path.join("images", filename)
     photo = models.ImageField(verbose_name=u'Poster',
                               upload_to=get_file_path,
                               max_length=256,
                               blank=True,
                               null=True)
     photo_small = ImageSpecField(
         [Adjust(contrast=1.2, sharpness=1.1),
          ResizeToFill(50, 50)],
         image_field='photo',
         format='JPEG',
         options={'quality': 90})
     photo_medium = ImageSpecField(
         [Adjust(contrast=1.2, sharpness=1.1),
          ResizeToFit(300, 200)],
         image_field='photo',
         format='JPEG',
         options={'quality': 90})
     photo_big = ImageSpecField(
         [Adjust(contrast=1.2, sharpness=1.1),
          ResizeToFit(640, 480)],
         image_field='photo',
         format='JPEG',
         options={'quality': 90})
예제 #20
0
파일: models.py 프로젝트: sokogfb/1source
class JournalEntry(models.Model):
    title = models.CharField(max_length=150)
    slug = AutoSlugField(populate_from='title',
                         editable=False,
                         always_update=True,
                         unique=True,
                         null=True)
    image = models.ImageField(upload_to='journal')
    image_web = ImageSpecField(source='image',
                               processors=[ResizeToFit(width=500)],
                               format='JPEG',
                               options={'quality': 75})
    image_mobile = ImageSpecField(source='image',
                                  processors=[ResizeToFit(width=320)],
                                  format='JPEG',
                                  options={'quality': 68})
    body = RichTextField()
    published_date = models.DateField()

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return '/journal/' + self.slug + '/'

    class Meta:
        verbose_name = 'Journal entry'
        verbose_name_plural = 'Journal entries'
예제 #21
0
class VariantImage(models.Model):
    product = models.ForeignKey(ProductVariant,
                                on_delete=models.DO_NOTHING,
                                db_index=True)
    created_at = models.DateTimeField('date created', auto_now_add=True)
    link = models.ImageField(upload_to=upload_to)
    full = ImageSpecField(source='link',
                          processors=[],
                          format='PNG',
                          options={'quality': 60})
    thumbnail = ImageSpecField(source='link',
                               processors=[ResizeToFit(270, 270)],
                               format='PNG',
                               options={'quality': 60})
    paging = ImageSpecField(source='link',
                            processors=[ResizeToFit(147, 143)],
                            format='PNG',
                            options={'quality': 60})
    is_delete = models.BooleanField(default=False, blank=True)

    def __str__(self):
        return "{} - {}".format(self.product.pk, self.product.title)

    class Meta:
        verbose_name = 'Изображение варианта товара'
        verbose_name_plural = 'Изображения вариантов товаров'
예제 #22
0
class CarouselImage(models.Model):
    """
    Image to display on the carousel slide
    Instantiate only two
    """
    image = ProcessedImageField(upload_to='albums', processors=[ResizeToFit(1280)], format='JPEG', options={'quality': 70})
    thumb = ProcessedImageField(upload_to='albums', processors=[ResizeToFit(300)], format='JPEG', options={'quality': 80})
    created = models.DateTimeField(auto_now_add=True)
예제 #23
0
class Photo(models.Model):
    """Photo model"""
    LICENSES = (
        ('http://creativecommons.org/licenses/by/2.0/',         'CC Attribution'),
        ('http://creativecommons.org/licenses/by-nd/2.0/',      'CC Attribution-NoDerivs'),
        ('http://creativecommons.org/licenses/by-nc-nd/2.0/',   'CC Attribution-NonCommercial-NoDerivs'),
        ('http://creativecommons.org/licenses/by-nc/2.0/',      'CC Attribution-NonCommercial'),
        ('http://creativecommons.org/licenses/by-nc-sa/2.0/',   'CC Attribution-NonCommercial-ShareAlike'),
        ('http://creativecommons.org/licenses/by-sa/2.0/',      'CC Attribution-ShareAlike'),
    )
    title = models.CharField(max_length=255)
    slug = models.SlugField()
    photo = models.ImageField(upload_to="photos")
    photo_thumbnail = ImageSpecField(source='photo',
        processors=[ResizeToFit(460),Adjust(color=1.1)],
        format='JPEG',
        options={'quality': 75})
    photo_admin_thumbnail = ImageSpecField(source='photo',
        processors=[ResizeToFit(100),Adjust(color=1.1)],
        format='JPEG',
        options={'quality': 60})
    #photo_display = ImageSpecField(source='photo',
    #    processors=[ResizeToFit(1024)],
    #    format='JPEG',
    #    options={'quality': 90})
    taken_by = models.CharField(max_length=100, blank=True)
    license = models.URLField(blank=True, choices=LICENSES)
    description = models.TextField(blank=True)
    tags = TagField()
    uploaded = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    _exif = models.TextField(blank=True) 

    class Meta:
        db_table = 'media_photos'

    def _set_exif(self, d):
        self._exif = simplejson.dumps(d)

    def _get_exif(self):
        if self._exif:
            return simplejson.loads(self._exif)
        else:
            return {}

    exif = property(_get_exif, _set_exif, "Photo EXIF data, as a dict.")

    def __unicode__(self):
        return '%s' % self.title

    @property
    def url(self):
        return '%s%s' % (settings.MEDIA_URL, self.photo)

    @permalink
    def get_absolute_url(self):
        return ('photo_detail', None, { 'slug': self.slug })
예제 #24
0
class Organization(TimeStampedModel):
    uuid = models.UUIDField(_('UUID'),
                            default=uuid.uuid4,
                            editable=False,
                            unique=True)
    name = models.CharField(_('name'), max_length=255)
    description = models.TextField(_('description'), blank=True)
    code = models.SlugField(_('code'),
                            blank=True,
                            allow_unicode=True,
                            unique=True)
    phone_number = PhoneNumberField(_('phone number'), blank=True)
    email = models.EmailField(_('email'), blank=True)
    avatar = models.ImageField(_('avatar'),
                               blank=True,
                               null=True,
                               upload_to='organizations/avatars')
    avatar_thumbnail = ImageSpecField(source='avatar',
                                      processors=[ResizeToFit(100, 100)],
                                      format='PNG',
                                      options={'quality': 100})
    avatar_sm = ImageSpecField(source='avatar',
                               processors=[ResizeToFit(50, 50)],
                               format='PNG',
                               options={'quality': 100})
    website = models.URLField(_('website'), blank=True)
    country = CountryField(_('country'), blank=True)
    address = models.TextField(_('address'), blank=True)
    members = models.ManyToManyField(settings.AUTH_USER_MODEL,
                                     verbose_name=_('members'),
                                     related_name='organizations',
                                     related_query_name='organization',
                                     blank=True)
    tags = ArrayField(models.CharField(max_length=50),
                      verbose_name=_('tags'),
                      blank=True,
                      default=list)
    creator = models.ForeignKey(settings.AUTH_USER_MODEL,
                                verbose_name=_('creator'),
                                blank=True,
                                related_name='created_organizations',
                                related_query_name='created_organization',
                                on_delete=models.CASCADE)
    extras = JSONField(_('extras'), blank=True, default=dict)

    class Meta:
        verbose_name = _('Organization')
        verbose_name_plural = _('Organizations')
        ordering = ['-created_at']

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if not self.code:
            self.code = slugify(self.name[:50])
        super().save(*args, **kwargs)
예제 #25
0
class AlbumImage(models.Model):
    image = ProcessedImageField(upload_to='albums', processors=[ResizeToFit(1280)], format='JPEG', options={'quality': 60})#adding an image to an album
    thumb = ProcessedImageField(upload_to='albums', processors=[ResizeToFit(500)], format='JPEG', options={'quality': 70})# an alternative image for the first one
    album = models.ForeignKey('album', on_delete=models.PROTECT)#this is the connecter to the first album table
    alt = models.CharField(max_length=255, default=uuid.uuid4)#creates a universal identifier to the album model
    created = models.DateTimeField(auto_now_add=True)
    width = models.IntegerField(default=0)# sets the image width
    height = models.IntegerField(default=0)# sets the image height
    slug = models.SlugField(max_length=71, default=uuid.uuid4, editable=False)#not neccesary here
예제 #26
0
파일: models.py 프로젝트: acskang/madie
class AlbumImage(models.Model):
    image = ProcessedImageField(upload_to='albums', processors=[ResizeToFit(1280)], format='JPEG', options={'quality': 70})
    thumb = ProcessedImageField(upload_to='albums', processors=[ResizeToFit(300)], format='JPEG', options={'quality': 80})
    album = models.ForeignKey('album', on_delete=models.PROTECT)
    alt = models.CharField(max_length=255, default=uuid.uuid4)
    created = models.DateTimeField(auto_now_add=True)
    width = models.IntegerField(default=0)
    height = models.IntegerField(default=0)
    slug = models.SlugField(max_length=70, default=uuid.uuid4, editable=False)
예제 #27
0
파일: models.py 프로젝트: simone/upy
def _choose_preprocessor():
    """
    Function to define the preprocessor on original_image field. It crops the original image, so user
    cannot save on server too big images. (in order to prevent disk space wasting)
    """
    if settings.USE_FULLHD_SUPPORT:
        return ResizeToFit(width=1920, height=1366)  #upscale=False)
    else:
        return ResizeToFit(width=800, height=800)  #upscale=False)
예제 #28
0
class File(core.models.Model):
    file = models.FileField()
    filename = models.CharField(max_length=255, blank=True, null=True)

    contribution = django.contrib.contenttypes.fields.GenericRelation(
        'contributions.Contribution',
        content_type_field='contribution_type',
        object_id_field='contribution_id',
        related_query_name='file')

    version = models.ForeignKey('content2.Version',
                                null=True,
                                on_delete=models.CASCADE,
                                related_name='file')

    image_480 = ImageSpecField(source='file',
                               processors=[Transpose(),
                                           ResizeToFit(480)],
                               format='JPEG')
    image_768 = ImageSpecField(source='file',
                               processors=[Transpose(),
                                           ResizeToFit(768)],
                               format='JPEG')
    image_1200 = ImageSpecField(source='file',
                                processors=[Transpose(),
                                            ResizeToFit(1200)],
                                format='JPEG')
    image_1920 = ImageSpecField(source='file',
                                processors=[Transpose(),
                                            ResizeToFit(1920)],
                                format='JPEG')

    objects = FileManager()

    @property
    def display_name(self):
        return self.filename or path.basename(self.file.name)

    def __str__(self):
        return self.display_name

    def get_absolute_url(self):
        return self.file.url

    def is_image(self):
        root, ext = path.splitext(self.file.name.lower())
        return ext in ('.svg', '.apng', '.png', '.gif', '.jpg', '.jpeg')

    def is_video(self):
        root, ext = path.splitext(self.file.name.lower())
        return ext in ('.mp4', '.ogg', '.webm')

    def is_audio(self):
        root, ext = path.splitext(self.file.name.lower())
        return ext in ('.opus', '.ogg', '.aac', '.mp3', '.flac', '.m4a')
예제 #29
0
class News(models.Model):
    permalink = models.SlugField('パーマリンク (アドレス名)',
                                 max_length=50,
                                 primary_key=True,
                                 unique=True)
    title = models.CharField('投稿タイトル', max_length=100)
    description = models.TextField('説明', blank=True, null=True)
    content = MarkdownxField('本文 (Markdown形式)')
    # .containerの最大幅x2, Google構造化データ用
    image = ProcessedImageField(verbose_name='画像',
                                blank=True,
                                null=True,
                                upload_to='main/news/',
                                processors=[ResizeToFit(1900, 1900)],
                                format='JPEG',
                                options={'quality': 85})
    # .containerの最大幅
    image_large = ImageSpecField(source='image',
                                 processors=[ResizeToFit(950, 950)],
                                 format='JPEG',
                                 options={'quality': 85})
    # SPのメイン画像,PCのサムネイル画像
    image_medium = ImageSpecField(source='image',
                                  processors=[ResizeToFit(350, 350)],
                                  format='JPEG',
                                  options={'quality': 75})
    # SPのサムネイル画像
    image_small = ImageSpecField(source='image',
                                 processors=[ResizeToFit(150, 150)],
                                 format='JPEG',
                                 options={'quality': 60})
    published_at = models.DateTimeField('投稿公開日', default=now)
    is_draft = models.BooleanField('下書き', default=False)
    created_at = models.DateTimeField('投稿作成日', auto_now_add=True)
    updated_at = models.DateTimeField('投稿更新日', auto_now=True)

    def __str__(self):
        return self.title

    def formatted_markdown(self):
        return markdownify(self.content)

    # 保存時に実行
    def save(self, force_insert=False, force_update=False):
        super().save(force_insert, force_update)
        try:
            cache.clear()  # キャッシュをクリア
            # ping_google()  # Googleにサイトマップを送信
        except Exception:
            pass

    class Meta:
        verbose_name_plural = "News"
        ordering = ('-is_draft', '-published_at', 'title')
예제 #30
0
class Lightbox(models.Model):
    image = ProcessedImageField(upload_to='albums', processors=[ResizeToFit(1280)], 
                                format='JPEG', options={'quality': 100})
    thumb = ProcessedImageField(upload_to='albums', processors=[ResizeToFit(200)], 
                                format='JPEG', options={'quality': 70}, default='')
    album = models.ForeignKey('album', on_delete=models.PROTECT)
    alt = models.CharField(max_length=255, default='Photo_Ksenia_Sheen')
    created = models.DateTimeField(auto_now_add=True)
    width = models.IntegerField(default=0)
    height = models.IntegerField(default=0)
    slug = models.SlugField(max_length=70, editable=False, default='')
    def process_instance(self, image, instance): 


        #Step 1, crop based on crop position
        crop_value = self.get_crop_value(instance)
        original_width = image.size[0]
        original_height = image.size[1]
        
        # print 'process %s :: original width %s original height %s || SETTINGS %s - %s - %s upscale? %s crop? %s, %s, %s, %s'%(instance, original_width, original_height, self.width, self.height, self.resize_method, self.upscale, crop_value.x, crop_value.y, crop_value.width, crop_value.height)
        is_empty_cropper = crop_value == None or crop_value == '' or (crop_value.width==None and crop_value.height==None)
        if is_empty_cropper:
            #Set crop with inital crop.

            # print 'crop: %s, %s original: %s, %s'%(self.width, self.height, original_width, original_height)

            crop_w = self.width#width if self.width is None else self.width
            if self.height and not crop_w:
                crop_w = int(float(float(self.height) / float(original_height))*float(original_width))



            crop_h = self.height#height if self.height is None else self.height
            if self.width and not crop_h:
                crop_h = int(float(float(self.width) / float(original_width))*float(original_height))

            if self.resize_method == 'fit':
                # print "Resize to fit: %s, %s"%(crop_w, crop_h)
                resizer = ResizeToFit(crop_w, crop_h, None, self.upscale)            
            else:
                # print "Resize to fill: %s, %s"%(crop_w, crop_h)
                resizer = ResizeToFill(crop_w, crop_h, None, self.upscale)

            resized = resizer.process(image)
            return resized
            
            
        crop_x = 0 if crop_value.x is None else int(0-crop_value.x)
        crop_y = 0 if crop_value.y is None else int(0-crop_value.y)
        crop_w = None if crop_value.width is None else int(crop_value.width)
        crop_h = None if crop_value.height is None else int(crop_value.height)

        # print "Resize canvas: %s, %s, %s, %s"%(crop_x, crop_y, crop_w, crop_h)
        cropper = ResizeCanvas(crop_w, crop_h, None, None, crop_x, crop_y)
        cropped = cropper.process(image)
       

        

        #Step 2, resize to correct width and height:
        if self.resize_method == 'fit':
            width = None if not self.width else self.width
            height = None if not self.height else self.height
            if height==None:
                # print 'height = (%s/%s) * %s'%(width, original_width, original_height)
                height = int(float(float(width)/float(original_width)) * float(original_height))
            elif width==None:
                width = int(float(float(height)/float(original_height)) * float(original_width))


            # print "Resize to fit: %s, %s"%(width, height)
            resizer = ResizeToFit(width, height, None, self.upscale)            
        else:
            width = cropped.size[0] if not self.width else self.width
            height = cropped.size[1] if not self.height else self.height
            # print "Resize to fill: %s, %s"%(crop_w, crop_h)
            resizer = ResizeToFill(width, height, None, self.upscale)
        
        # print 'Resize to %s - %s (%s - %s)'%(width, height, resizer.width, resizer.height)
        resized = resizer.process(cropped)
        return resized
예제 #32
0
파일: models.py 프로젝트: yigor/i-help-u
 def process(self, img):
     if img.size[0] < 250 or img.size[1] < 250:
         actual_processor = ResizeToFit(250, 250)
     else:
         actual_processor = SmartResize(250, 250)
     return actual_processor.process(img)