class MediaFileBase(Base, TranslatedObjectMixin): """ Abstract media file class. Inherits from :class:`feincms.module.Base` because of the (handy) extension mechanism. """ from django.core.files.storage import FileSystemStorage default_storage_class = getattr(django_settings, 'DEFAULT_FILE_STORAGE', 'django.core.files.storage.FileSystemStorage') default_storage = get_callable(default_storage_class) fs = default_storage(location = settings.FEINCMS_MEDIALIBRARY_ROOT, base_url = settings.FEINCMS_MEDIALIBRARY_URL) sizes = getattr(django_settings, 'MEDIALIBRARY_IMAGESIZES', ()) file = ImageWithThumbsField(_('file'), sizes = sizes, max_length = 255, upload_to = settings.FEINCMS_MEDIALIBRARY_UPLOAD_TO, storage = fs) type = models.CharField(_('file type'), max_length = 12, editable = False, choices = ()) created = models.DateTimeField(_('created'), editable = False, default = datetime.now) copyright = models.CharField(_('copyright'), max_length = 200, blank = True) file_size = models.IntegerField(_("file size"), blank = True, null = True, editable = False) categories = models.ManyToManyField(Category, verbose_name = _('categories'), blank = True, null = True) categories.category_filter = True licence = models.ForeignKey(Licence, null=True) source_url = models.CharField(max_length=400, blank=True, null=True) class Meta: abstract = True verbose_name = _('media file') verbose_name_plural = _('media files') objects = TranslatedObjectManager() filetypes = [ ] filetypes_dict = { } def formatted_file_size(self): return filesizeformat(self.file_size) formatted_file_size.short_description = _("file size") formatted_file_size.admin_order_field = 'file_size' def formatted_created(self): return self.created.strftime("%Y-%m-%d %H:%M") formatted_created.short_description = _("created") formatted_created.admin_order_field = 'created' @classmethod def reconfigure(cls, upload_to = None, storage = None): f = cls._meta.get_field('file') # Ugh. Copied relevant parts from django/db/models/fields/files.py # FileField.__init__ (around line 225) if storage: f.storage = storage if upload_to: f.upload_to = upload_to if callable(upload_to): f.generate_filename = upload_to @classmethod def register_filetypes(cls, *types): cls.filetypes[0:0] = types choices = [ t[0:2] for t in cls.filetypes ] cls.filetypes_dict = dict(choices) cls._meta.get_field('type').choices[:] = choices def __init__(self, *args, **kwargs): super(MediaFileBase, self).__init__(*args, **kwargs) if self.file and self.file.path: self._original_file_path = self.file.path def __unicode__(self): trans = None # This might be provided using a .extra() clause to avoid hundreds of extra queries: if hasattr(self, "preferred_translation"): trans = getattr(self, "preferred_translation", u"") else: try: trans = unicode(self.translation) except models.ObjectDoesNotExist: pass except AttributeError, e: pass if trans: return trans else: return os.path.basename(self.file.name)
class Project(models.Model, TranslatedObjectMixin): """ An encapsualtion of a project. """ categories = models.ManyToManyField(Category, verbose_name=_("categories")) client = models.ForeignKey(Client, verbose_name=_("client"), blank=True, null=True) files = models.ManyToManyField(File, blank=True, verbose_name=_("files"), through='ProjectFile') media_category = models.ForeignKey(Folder, blank=True, null=True, verbose_name=_("media category")) services = models.ManyToManyField(Service, blank=True, verbose_name=_("services")) created = models.DateField(blank=True, null=True) featured = models.BooleanField(default=False) active = models.BooleanField(default=True) objects = TranslatedObjectManager() class Meta: ordering = ('-created', ) verbose_name = _('project') verbose_name_plural = _('projects') def get_main_file(self): qs = ProjectFile.objects.filter(featured=True, project=self) if qs.count() > 0: return qs[0] else: return None def get_other_files(self): qs = self.files.all() if qs.count() > 1: return qs[1:qs.count()] else: return None def __unicode__(self): trans = None if hasattr(self, "preferred_translation"): trans = getattr(self, "preferred_translation", u"") else: try: trans = unicode(self.translation) except models.ObjectDoesNotExist: pass except AttributeError, e: pass if trans: return trans else: return u"[ no name ]"
class MediaFileBase(Base, TranslatedObjectMixin): # XXX maybe have a look at settings.DEFAULT_FILE_STORAGE here? from django.core.files.storage import FileSystemStorage fs = FileSystemStorage(location=settings.FEINCMS_MEDIALIBRARY_ROOT, base_url=settings.FEINCMS_MEDIALIBRARY_URL) file = models.FileField(_('file'), max_length=255, upload_to=settings.FEINCMS_MEDIALIBRARY_UPLOAD_TO, storage=fs) type = models.CharField(_('file type'), max_length=12, editable=False, choices=()) created = models.DateTimeField(_('created'), editable=False, default=datetime.now) copyright = models.CharField(_('copyright'), max_length=200, blank=True) file_size = models.IntegerField(_("file size"), blank=True, null=True, editable=False) categories = models.ManyToManyField(Category, verbose_name=_('categories'), blank=True, null=True) categories.category_filter = True class Meta: abstract = True verbose_name = _('media file') verbose_name_plural = _('media files') objects = TranslatedObjectManager() filetypes = [ ] filetypes_dict = { } def get_categories_as_string(self): categories_tmp = self.categories.values_list('title', flat=True) return ', '.join(categories_tmp) get_categories_as_string.short_description = _('categories') def formatted_file_size(self): return filesizeformat(self.file_size) formatted_file_size.short_description = _("file size") def formatted_created(self): return self.created.strftime("%Y-%m-%d %H:%M") formatted_created.short_description = _("created") formatted_created.admin_order_field = 'created' @classmethod def reconfigure(cls, upload_to=None, storage=None): f = cls._meta.get_field('file') # Ugh. Copied relevant parts from django/db/models/fields/files.py # FileField.__init__ (around line 225) if storage: f.storage = storage if upload_to: f.upload_to = upload_to if callable(upload_to): f.generate_filename = upload_to @classmethod def register_filetypes(cls, *types): cls.filetypes[0:0] = types choices = [ t[0:2] for t in cls.filetypes ] cls.filetypes_dict = dict(choices) cls._meta.get_field('type').choices[:] = choices def __unicode__(self): trans = None # This might be provided using a .extra() clause to avoid hundreds of extra queries: if hasattr(self, "preferred_translation"): trans = getattr(self, "preferred_translation", u"") else: try: trans = unicode(self.translation) except models.ObjectDoesNotExist: pass except AttributeError, e: pass if trans: return trans else: return os.path.basename(self.file.name)
class Person(models.Model, TranslatedObjectMixin): """ Model of a team member. """ title_prefix = models.CharField(max_length=127, blank=True, verbose_name=u"Titul před jménem", help_text=u"Například: Ing.") first_name = models.CharField(max_length=127, verbose_name=u"Jméno", help_text=u"Například: Martin") last_name = models.CharField(max_length=127, verbose_name=u"Příjmení", help_text=u"Například: Kocourek") title_suffix = models.CharField(max_length=127, blank=True, verbose_name=u"Titul za jménem", help_text=u"Například: PhD.") nick_name = models.SlugField(max_length=127, verbose_name=u"Nickname", help_text=u"Například: fanda") email = models.EmailField(blank=True, verbose_name=u"E-mail", help_text=u"Př.: [email protected]") photo = models.ImageField( upload_to="team", blank=True, verbose_name=u"Fotografie", help_text= u"Použijte obrázky ve formátu JPEG, GIF nebo PNG. Obrázky se automaticky zmenší na požadovaný rozměr." ) category = models.CharField(max_length=127, verbose_name=u"Kategorie", help_text=u"Pro členění na stránce.", default="1", choices=PERSON_CATEGORIES) sort_order = models.PositiveIntegerField( verbose_name=u"Pořadí", blank=True, null=True, help_text= u"Nepovinný údaj pro možnost vlastního řazení. Pokud má více zaměstnanců stejné pořadové číslo, řadí se zaměstnanci abecedně dle příjmení." ) active = models.BooleanField( default=True, verbose_name=u"Je aktivní?", help_text=u"Neaktivní karty zaměstnance se nezobrazí na stránce.") objects = TranslatedObjectManager() class Meta: ordering = [ 'sort_order', 'last_name', ] verbose_name = _("Team member") verbose_name_plural = _("Team members") def full_name(self): return u'%s %s %s %s' % (self.title_prefix, self.last_name, self.first_name, self.title_suffix) @property def display(self): return u'%s %s' % (self.first_name, self.last_name) def get_absolute_url(self): from leonardo.module.web.widget.application.reverse import app_reverse return app_reverse('project_team_detail', 'team.apps.team', kwargs={ 'person_nick_name': self.nick_name, }) def __unicode__(self): return u'%s %s' % (self.first_name, self.last_name)
class MediaFileBase(models.Model, ExtensionsMixin, TranslatedObjectMixin): """ Abstract media file class. Includes the :class:`feincms.models.ExtensionsMixin` because of the (handy) extension mechanism. """ file = models.FileField(_('file'), max_length=255, upload_to=settings.FEINCMS_MEDIALIBRARY_UPLOAD_TO) type = models.CharField(_('file type'), max_length=12, editable=False, choices=()) created = models.DateTimeField(_('created'), editable=False, default=timezone.now) copyright = models.CharField(_('copyright'), max_length=200, blank=True) file_size = models.IntegerField(_("file size"), blank=True, null=True, editable=False) categories = models.ManyToManyField(Category, verbose_name=_('categories'), blank=True) categories.category_filter = True class Meta: abstract = True ordering = ['-created'] verbose_name = _('media file') verbose_name_plural = _('media files') objects = TranslatedObjectManager() filetypes = [] filetypes_dict = {} @classmethod def reconfigure(cls, upload_to=None, storage=None): f = cls._meta.get_field('file') # Ugh. Copied relevant parts from django/db/models/fields/files.py # FileField.__init__ (around line 225) if storage: f.storage = storage if upload_to: f.upload_to = upload_to if callable(upload_to): f.generate_filename = upload_to @classmethod def register_filetypes(cls, *types): cls.filetypes[0:0] = types choices = [t[0:2] for t in cls.filetypes] cls.filetypes_dict = dict(choices) cls._meta.get_field('type').choices[:] = choices def __init__(self, *args, **kwargs): super(MediaFileBase, self).__init__(*args, **kwargs) if self.file: self._original_file_name = self.file.name def __str__(self): trans = None try: trans = self.translation except models.ObjectDoesNotExist: pass except AttributeError: pass if trans: trans = '%s' % trans if trans.strip(): return trans return os.path.basename(self.file.name) def get_absolute_url(self): return self.file.url def determine_file_type(self, name): """ >>> t = MediaFileBase() >>> str(t.determine_file_type('foobar.jpg')) 'image' >>> str(t.determine_file_type('foobar.PDF')) 'pdf' >>> str(t.determine_file_type('foobar.jpg.pdf')) 'pdf' >>> str(t.determine_file_type('foobar.jgp')) 'other' >>> str(t.determine_file_type('foobar-jpg')) 'other' """ for type_key, type_name, type_test in self.filetypes: if type_test(name): return type_key return self.filetypes[-1][0] def save(self, *args, **kwargs): if not self.id and not self.created: self.created = timezone.now() self.type = self.determine_file_type(self.file.name) if self.file: try: self.file_size = self.file.size except (OSError, IOError, ValueError) as e: logger.error("Unable to read file size for %s: %s" % (self, e)) super(MediaFileBase, self).save(*args, **kwargs) logger.info("Saved mediafile %d (%s, type %s, %d bytes)" % (self.id, self.file.name, self.type, self.file_size or 0)) # User uploaded a new file. Try to get rid of the old file in # storage, to avoid having orphaned files hanging around. if getattr(self, '_original_file_name', None): if self.file.name != self._original_file_name: self.delete_mediafile(self._original_file_name) self.purge_translation_cache() save.alters_data = True def delete_mediafile(self, name=None): if name is None: name = self.file.name try: self.file.storage.delete(name) except Exception as e: logger.warn("Cannot delete media file %s: %s" % (name, e))
class MediaFileBase(models.Model, ExtensionsMixin, TranslatedObjectMixin): """ Abstract media file class. Includes the :class:`feincms.models.ExtensionsMixin` because of the (handy) extension mechanism. """ file = models.FileField(_('file'), max_length=255, upload_to=settings.FEINCMS_MEDIALIBRARY_UPLOAD_TO) type = models.CharField(_('file type'), max_length=12, editable=False, choices=()) created = models.DateTimeField(_('created'), editable=False, default=datetime.now) copyright = models.CharField(_('copyright'), max_length=200, blank=True) file_size = models.IntegerField(_("file size"), blank=True, null=True, editable=False) categories = models.ManyToManyField(Category, verbose_name=_('categories'), blank=True, null=True) categories.category_filter = True class Meta: abstract = True ordering = ['-created'] verbose_name = _('media file') verbose_name_plural = _('media files') objects = TranslatedObjectManager() filetypes = [ ] filetypes_dict = { } def formatted_file_size(self): return filesizeformat(self.file_size) formatted_file_size.short_description = _("file size") formatted_file_size.admin_order_field = 'file_size' def formatted_created(self): return self.created.strftime("%Y-%m-%d") formatted_created.short_description = _("created") formatted_created.admin_order_field = 'created' @classmethod def reconfigure(cls, upload_to=None, storage=None): f = cls._meta.get_field('file') # Ugh. Copied relevant parts from django/db/models/fields/files.py # FileField.__init__ (around line 225) if storage: f.storage = storage if upload_to: f.upload_to = upload_to if callable(upload_to): f.generate_filename = upload_to @classmethod def register_filetypes(cls, *types): cls.filetypes[0:0] = types choices = [ t[0:2] for t in cls.filetypes ] cls.filetypes_dict = dict(choices) cls._meta.get_field('type').choices[:] = choices def __init__(self, *args, **kwargs): super(MediaFileBase, self).__init__(*args, **kwargs) if self.file: self._original_file_name = self.file.name def __unicode__(self): trans = None try: trans = self.translation except models.ObjectDoesNotExist: pass except AttributeError: pass if trans: trans = unicode(trans) if trans.strip(): return trans return os.path.basename(self.file.name) def get_absolute_url(self): return self.file.url def file_type(self): t = self.filetypes_dict[self.type] if self.type == 'image': # get_image_dimensions is expensive / slow if the storage is not local filesystem (indicated by availability the path property) try: self.file.path except NotImplementedError: return t try: from django.core.files.images import get_image_dimensions d = get_image_dimensions(self.file.file) if d: t += " %d×%d" % ( d[0], d[1] ) except IOError, e: t += " (%s)" % e.strerror return t