class Image(models.Model): image = ThumbnailerField(upload_to='images') caption = models.CharField(max_length=500, blank=True, null=True) content_object = models.ForeignKey(ContentObject, related_name='images') def __unicode__(self): return self.caption
class SpeakerLinkType(models.Model): name = models.CharField("발표자 링크 유형", max_length=20) img_icon = ThumbnailerField("링크 아이콘 이미지", upload_to="speaker/icon", blank=True) class Meta: verbose_name = "발표자 링크 유형" verbose_name_plural = f"{verbose_name} 목록" def __str__(self): return self.name
class Post(models.Model): title = models.CharField(max_length=120) content = models.CharField(max_length=400) picture = ThumbnailerField(_('Main image'), max_length=200, upload_to='pictures/') author = models.ForeignKey(get_user_model(), related_name='posts', on_delete=models.CASCADE) date_added = models.DateTimeField(_(u'Date Added'), auto_now_add=True) date_updated = models.DateTimeField(_(u'Date Updated'), auto_now=True) def __str__(self): return "Post {}".format(self.title)
class CarouselImage(models.Model): TARGET_CHOICES = ( ('_blank', 'New Window'), ('_self', 'Same Window'), ) title = models.CharField(max_length=100, blank=True, null=True) description = models.CharField(max_length=500, blank=True, null=True) link = models.URLField(blank=True, null=True) target = models.CharField(max_length=10, choices=TARGET_CHOICES) image = ThumbnailerField(upload_to='carousel_images') carousel = models.ForeignKey(Carousel, related_name="images") def __unicode__(self): return self.title
class MonFichier(models.Model): name = models.CharField(max_length=100, blank=True) file = ThumbnailerField(max_length=100, upload_to='mon-fichier/%Y-%m-%d') description = models.TextField(blank=True) user = models.ForeignKey(User, default=1, related_name='user_files') # automatic fields created_at = models.DateTimeField(auto_now_add=True, help_text=u'Created') updated_at = models.DateTimeField(auto_now=True, help_text=u'Updated') objects = MonFichierManager() class Meta: verbose_name_plural = 'Mes Fichiers' def __unicode__(self): return self.name
class ProductPhoto(models.Model): product = models.ForeignKey('product.Product', verbose_name=_('Продукт')) photo = ThumbnailerField(blank=True, null=True, default=None, upload_to=get_photo_path, verbose_name=_('Фото')) objects = ProductPhotoManager() def get_preview(self): return self.photo['product_small'].url if self.photo else None def get_big(self): return self.photo['product_big'].url if self.photo else None class Meta: verbose_name = _('Фото продукта') verbose_name_plural = _('Фото продуктов')
class Profile(LocationMixin): LOCATION_PRIVACY_CHOICES = ( ('none', "Private - Don't share my location at all"), ('anonymous', "Anonymous - Share my location anonymously"), ('public', "Public - Share my location with my profile information"), ) user = models.OneToOneField(User) photo = ThumbnailerField(upload_to='profile_photos', blank=True) bio = models.TextField(blank=True, null=True) city = models.CharField(max_length=200, blank=True) interests = models.ManyToManyField(Interest, blank=True, null=True) location_privacy = models.CharField(max_length=20, default='anonymous', choices=LOCATION_PRIVACY_CHOICES) def __unicode__(self): return u"User profile for %s" % self.user
class SocialLink(PositionModel): SOCIAL_CHOICES = Choices(('vk', "VK"), ('fb', "Facebook"), ('tw', "Twitter"), ('gplus', "Google+"), ('youtube', "Youtube"), ('instagram', "Instagram")) name = models.CharField(verbose_name=_('name'), max_length=512, choices=SOCIAL_CHOICES, default='') url = models.URLField(verbose_name=_('url'), default='') icon = ThumbnailerField(verbose_name=_('icon'), upload_to='icons/social/') def __str__(self): return self.get_name_display() class Meta: ordering = ('position', ) verbose_name = _('social link') verbose_name_plural = _('social links')
class File(models.Model): folder = models.ForeignKey('filebase.Folder', null=True, on_delete=models.CASCADE, default=None, blank=True, verbose_name=_("Folder")) file = ThumbnailerField(_('File'), upload_to=conf.UPLOAD_TO, storage=conf.FILE_STORAGE, thumbnail_storage=conf.THUMBNAIL_STORAGE) name = models.CharField( _('name'), max_length=255, blank=True, default='', ) filename = models.CharField( _('filename'), max_length=255, help_text=_(u'Use for renaming your file on the server'), blank=False, ) # additional system infos uploader = models.ForeignKey( getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), null=True, on_delete=models.SET_NULL, blank=True, related_name='owned_files', verbose_name=_('Uploader'), ) created = models.DateTimeField(_('Created'), default=timezone.now) modified = models.DateTimeField(_('Modified'), auto_now=True) # meta info type = models.CharField(_('File type'), max_length=12, choices=(), blank=True) extension = models.CharField(_('Extension'), max_length=255, blank=True, default='') author = models.CharField(_('Author'), max_length=255, blank=True, default='') copyright = models.CharField(_('Copyright'), max_length=255, blank=True, default='') file_hash = models.CharField(_('Checksum'), help_text=_(u'For preventing duplicates'), max_length=40, blank=False, unique=True) def __str__(self): return '%s' % self.filename class Meta: verbose_name = _(u'File') verbose_name_plural = _(u'Files') def save(self, *args, **kwargs): if not self.filename: self.filename = self.file.file super(File, self).save(*args, **kwargs) # you should not change extensions! def clean(self, *args, **kwargs): super(File, self).clean(*args, **kwargs) if (self.id): old_instance = File.objects.get(pk=self.id) if not old_instance.filename == self.filename: self.filename = get_valid_filename(self.filename) old_name, old_extension = os.path.splitext( old_instance.filename) new_name, new_extension = os.path.splitext(self.filename) if not old_extension.lower() == new_extension.lower(): raise ValidationError( _("File extension must stay the same.")) def generate_file_hash(self): self.file_hash = sha1_from_file(self.file) @property def is_image(self): if self.file: image_definition = conf.FILE_TYPES.get('image', None) if image_definition is not None: if self.extension in image_definition.get('extensions'): return True return False @property def label(self): if self.name: return '%s (%s)' % (self.name, self.filename) else: return self.filename @property def admin_url(self): return urlresolvers.reverse('admin:filebase_file_change', args=(self.pk, )) @property def thumb_field_url(self): if self.is_image: return self._thumb_url(*conf.IMAGE_SIZES['FIELD']) else: return @property def thumb_list_url(self): if self.is_image: return self._thumb_url(*conf.IMAGE_SIZES['LIST']) else: return def thumb_list(self): if self.is_image: url = self.thumb_list_url return '<a href="%s" target="_blank"><img src="%s" alt="%s"></a>' \ % (self.file.url, url, self.label) else: return thumb_list.allow_tags = True thumb_list.short_description = _(u'Thumb') def references_list(self): links = [ rel.get_accessor_name() for rel in model_get_all_related_objects(File) ] total = 0 for link in links: total += getattr(self, link).all().count() if total > 0: return "%sx" % total else: return "-" references_list.allow_tags = True references_list.short_description = _(u'Referenced?') def get_json_response(self): return { 'id': self.id, 'file_url': self.file.url, 'edit_url': self.admin_url, 'thumbnail_list': self.thumb_list_url, 'thumbnail_field': self.thumb_field_url, 'label': self.label, } def _thumb_url(self, width, height): if self.file: thumbnailer = get_thumbnailer(self.file) thumbnail_options = {'size': (width, height)} try: # catch the value error when trying to resize a 600x1 pixel image # to 150x150 > PIL wants to do it 150x0, and then complains... thumb = thumbnailer.get_thumbnail(thumbnail_options) return thumb.url except ValueError: pass return '' @property def url(self): """ to make the model behave like a file field """ if self.file: return self.file.url return ''
class TestModel(models.Model): avatar = ThumbnailerField(upload_to='avatars') picture = ThumbnailerImageField(upload_to='pictures', resize_source=dict(size=(10, 10)))
class Profile(models.Model): avatar = ThumbnailerField(upload_to='avatars') logo = models.FileField(upload_to='avatars') class Meta: app_label = 'easy_thumbnails_tests'
class Attachment(TimestampModelMixin, models.Model): objects = AttachmentQuerySet.as_manager() library = models.ForeignKey(Library, verbose_name=_("Library"), on_delete=models.CASCADE) rank = models.IntegerField(verbose_name=_("Rank")) original_name = models.CharField(max_length=255, verbose_name=_("Original name")) file = ThumbnailerField(verbose_name=_("File"), upload_to=upload_path_handler) filesize = models.BigIntegerField(verbose_name=_("File size"), ) mimetype = models.CharField(verbose_name=_("File type"), max_length=200, blank=True) image_width = models.IntegerField(verbose_name=_("Image width"), blank=True, null=True) image_height = models.IntegerField(verbose_name=_("Image height"), blank=True, null=True) title = models.CharField(verbose_name=_("Name"), max_length=255, blank=True) caption = models.TextField(verbose_name=_("Caption"), blank=True) options = models.TextField(verbose_name=_("Options"), blank=True) class Meta: verbose_name = _("Attachment") verbose_name_plural = _("Attachments") ordering = ('-library', 'rank') index_together = (( 'library', 'rank', ), ) def __str__(self): return self.original_name @property def is_image(self): return self.image_width is not None @property def mimetype_info(self): return parse_mimetype(self.original_name) def save(self, *args, **kwargs): if not self.original_name: self.original_name = self.file.name if self.original_name: self.original_name = self.original_name[:255] self.mimetype = (mimetypes.guess_type(self.original_name)[0] or '')[:200] if self.rank is None: next_rank = self._rank_queryset().aggregate( max_rank=Max('rank'))['max_rank'] if next_rank is None: next_rank = 0 else: next_rank += 1 self.rank = next_rank else: if self.pk is None: self._rank_queryset().filter(rank__gte=self.rank).update( rank=F('rank') + 1) if self.file: self.filesize = self.file.size source = BytesIO(self.file.read()) try: image = Image.open(source) self.image_width, self.image_height = image.size except IOError: pass finally: self.file.seek(0) else: self.filesize = -1 self.image_width = None self.image_height = None return super().save(*args, **kwargs) def delete(self, *args, **kwargs): self._rank_queryset().filter(rank__gt=self.rank).update( rank=F('rank') - 1) return super().delete(*args, **kwargs) def move_to(self, position): if position == self.rank: return if self.rank > position: self._rank_queryset().filter( rank__lt=self.rank, rank__gte=position).update(rank=F('rank') + 1) else: self._rank_queryset().filter( rank__gt=self.rank, rank__lte=position).update(rank=F('rank') - 1) self.rank = position self.save() def _rank_queryset(self): return Attachment.objects.filter(library=self.library).order_by('rank')
class TestModel(models.Model): avatar = ThumbnailerField(upload_to='avatars')
class File(models.Model, mixins.IconsMixin): _icon = "file" folder = models.ForeignKey(Folder, related_name='all_files', null=True, blank=True) file = ThumbnailerField(upload_to=get_directory_name, null=True, blank=True, max_length=255) _file_type_plugin_name = models.CharField("file_type_plugin_name", max_length=128, null=True, blank=True, editable=False) _file_size = models.IntegerField(null=True, blank=True) sha1 = models.CharField(max_length=40, blank=True, default='') has_all_mandatory_data = models.BooleanField(default=False, editable=False) original_filename = models.CharField(max_length=255, blank=True, null=True) name = models.CharField(max_length=255, null=True, blank=True, verbose_name=_('Name')) description = models.TextField(null=True, blank=True, verbose_name=_('Description')) owner = models.ForeignKey(auth_models.User, related_name='owned_%(class)ss', null=True, blank=True, verbose_name=_('Owner')) uploaded_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) is_public = models.BooleanField(default=False) objects = FileManager() def __init__(self, *args, **kwargs): super(File, self).__init__(*args, **kwargs) self._old_is_public = self.is_public def delete_thumbnails(self): """ Delete all the thumbnails related to `instance.file` """ for thumb in self.file.get_source_cache().thumbnails.all(): os.remove(os.path.join(settings.MEDIA_ROOT, thumb.name)) thumb.delete() def _move_file(self, src_filer_prefix, dst_filer_prefix): """ Move the file from src to dst. If `os.dirname(dst)` does not exist it creates all the required directory. """ src = self.file.name dst = src.replace(src_filer_prefix, dst_filer_prefix) new_name = self.file.storage.save(dst, self.file) self.file.delete(save=False) self.file = new_name def generate_sha1(self): sha = hashlib.sha1() self.file.seek(0) sha.update(self.file.read()) self.sha1 = sha.hexdigest() def save(self, *args, **kwargs): # check if this is a subclass of "File" or not and set # _file_type_plugin_name if self.__class__ == File: # what should we do now? # maybe this has a subclass, but is being saved as a File instance # anyway. do we need to go check all possible subclasses? pass elif issubclass(self.__class__, File): self._file_type_plugin_name = self.__class__.__name__ # cache the file size try: self._file_size = self.file.size except: pass if self._old_is_public != self.is_public and \ self.pk: if self.is_public: self._move_file(filer_settings.FILER_PRIVATEMEDIA_PREFIX, filer_settings.FILER_PUBLICMEDIA_PREFIX) else: self._move_file(filer_settings.FILER_PUBLICMEDIA_PREFIX, filer_settings.FILER_PRIVATEMEDIA_PREFIX) self._old_is_public = self.is_public try: self.generate_sha1() except Exception,e: print e, type(3) super(File, self).save(*args, **kwargs)
class Category(NameModel, YMkey): MAX_DEPTH_LEVEL = 4 parent = models.ForeignKey("self", blank=True, null=True, related_name="children") click_count = models.IntegerField(default=0, verbose_name=_('Количество кликов')) shop_count = models.IntegerField(default=0, verbose_name=_('Количество магазинов')) goods_count = models.IntegerField(default=0, verbose_name=_('Количество товаров')) depth = models.IntegerField(default=0, verbose_name=_('Глубина наследования')) photo = ThumbnailerField(blank=True, null=True, default=None, upload_to=get_photo_path, verbose_name=_('Фото')) full_path = models.CharField(max_length=200, blank=True, null=True) cached_product_photo = models.CharField(blank=True, null=True, default=None, max_length=255, verbose_name=_('Временное фото')) objects = CategoryManager.from_queryset(CategoryQuerySet)() def _get_thumbnail(self): if self.photo: try: return self.photo.url except AttributeError: pass return None def get_preview(self): ''' Возвращает изображение категории или изображение рандомного товара одной из подкатегорий ''' if self.depth == self.MAX_DEPTH_LEVEL: return None thumbnail = self._get_thumbnail() if thumbnail: url = thumbnail elif self.cached_product_photo: url = self.cached_product_photo else: category = self parents = [self] depth = self.depth url = None # если у текущей категории нет продуктов, проходимся по подкатегориям # пока не найдем категорию у которой есть продукты или не упрёмся # в самую нижнюю категорию while depth <= self.MAX_DEPTH_LEVEL: nonempty_category = Category.objects.filter(parent__in=parents)\ .filter(product__isnull=False)\ .order_by('?').first() if nonempty_category: category = nonempty_category break parents = Category.objects.filter(parent__in=parents) depth += 1 try: # проходим по всем фото всех категорий пока не получим урл фото for product in category.product_set.order_by('?'): if product.productphoto_set.all(): for photo in product.productphoto_set.order_by('?'): if photo.photo.url: url = photo.photo.url self.cached_product_photo = url self.save() else: continue except AttributeError: pass return url def get_children(self): return Category.objects.filter(parent=self.pk) def get_url(self): return "/catalog/%d/" % self.pk def __str__(self): return self.name def __unicode__(self): return self.name class Meta: verbose_name = _('Категория') verbose_name_plural = _('Категории')