Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
page = Page.objects.get(pk=1)
self.create_pagecontent(page)
path = os.path.join(settings.MEDIA_ROOT, 'somefile.jpg')
f = open(path, 'wb')
f.write('blabla')
f.close()
category = Category.objects.create(title='Category', parent=None)
category2 = Category.objects.create(title='Something', parent=category)
self.assertEqual(unicode(category2), 'Category - Something')
self.assertEqual(unicode(category), 'Category')
mediafile = MediaFile.objects.create(file='somefile.jpg')
mediafile.categories = [category]
page.mediafilecontent_set.create(
mediafile=mediafile,
region='main',
position='block',
ordering=1)
self.assertContains(self.client.get('/admin/page/page/1/'), 'no caption')
mediafile.translations.create(caption='something',
language_code='%s-ha' % short_language_code())
mf = page.content.main[1].mediafile
self.assertEqual(mf.translation.caption, 'something')
self.assertEqual(mf.translation.short_language_code(), short_language_code())
('doc', _('Microsoft Word'), lambda f: re.compile(r'\.docx?$', re.IGNORECASE).search(f)),
('xls', _('Microsoft Excel'), lambda f: re.compile(r'\.xlsx?$', re.IGNORECASE).search(f)),
('ppt', _('Microsoft PowerPoint'), lambda f: re.compile(r'\.pptx?$', re.IGNORECASE).search(f)),
('other', _('Binary'), lambda f: True), # Must be last
)
# ------------------------------------------------------------------------
class MediaFile(MediaFileBase):
@classmethod
def register_extension(cls, register_fn):
register_fn(cls, MediaFileAdmin)
pass
# ------------------------------------------------------------------------
# ------------------------------------------------------------------------
class MediaFileTranslation(Translation(MediaFile)):
caption = models.CharField(_('caption'), max_length=200)
description = models.TextField(_('description'), blank=True)
class Meta:
verbose_name = _('media file translation')
verbose_name_plural = _('media file translations')
def __unicode__(self):
return self.caption
#-------------------------------------------------------------------------
class MediaFileTranslationInline(admin.StackedInline):
model = MediaFileTranslation
max_num = len(django_settings.LANGUAGES)
class MediaFileAdmin(admin.ModelAdmin):
if bname and not bname.startswith(".") and "." in bname:
fname, ext = os.path.splitext(bname)
wanted_dir = os.path.dirname(zi.filename)
target_fname = slugify(fname) + ext.lower()
info = {}
if is_export_file:
info = json.loads(zi.comment)
mf = None
if overwrite:
full_path = os.path.join(wanted_dir, target_fname)
try:
mf = MediaFile.objects.get(file=full_path)
mf.file.delete(save=False)
except MediaFile.DoesNotExist:
mf = None
if mf is None:
mf = MediaFile()
if overwrite:
mf.file.field.upload_to = wanted_dir
mf.copyright = info.get("copyright", "")
mf.file.save(target_fname, ContentFile(z.read(zi.filename)), save=False)
mf.save()
found_metadata = False
if is_export_file:
try:
for tr in info["translations"]:
found_metadata = True
mt, mt_created = MediaFileTranslation.objects.get_or_create(
def __init__(self, *args, **kwargs):
if not args and "to" not in kwargs:
args = (MediaFile,)
super(MediaFileForeignKey, self).__init__(*args, **kwargs)
def upload_image(request):
"""
image upload handler
Returns a HttpResponse whose content is JSON.
"""
result = {'result': False}
if request.method == 'POST' and request.FILES:
if request.FILES['file']:
# TODO: use form (validation)
file = request.FILES['file']
mf = MediaFile()
mf.file.save(file.name, ContentFile(file.file.read()))
mf.save()
result = {'result': True}
result['location'] = mf.get_absolute_url()
return HttpResponse(dumps(result),
content_type="application/json")
# ------------------------------------------------------------------------
# coding=utf-8
# ------------------------------------------------------------------------
from __future__ import absolute_import, unicode_literals
from django.contrib import admin
from .models import Category, MediaFile
from .modeladmins import CategoryAdmin, MediaFileAdmin
# ------------------------------------------------------------------------
admin.site.register(Category, CategoryAdmin)
admin.site.register(MediaFile, MediaFileAdmin)
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.db import models
from django.http import HttpResponse
from django.template.context import RequestContext
from django.template.loader import render_to_string
from django.utils.translation import ungettext_lazy, ugettext_lazy as _
from feincms.module.medialibrary.models import MediaFile
from .specs.legacy import DEFAULT_SPECS
__all__ = ['Gallery', 'GalleryMediaFile', 'GalleryContent', 'DEFAULT_SPECS']
class Gallery(models.Model):
title = models.CharField(max_length=30)
images = models.ManyToManyField(MediaFile, through='GalleryMediaFile')
def ordered_images(self):
return self.images.select_related().all()\
.order_by('gallerymediafile__ordering')
def count_images(self):
if not getattr(self, '_image_count', None):
self._image_count = self.images.count()
return self._image_count
def verbose_images(self):
count = self.count_images()
return ungettext_lazy('%(count)d Image',
'%(count)d Images', count) % {'count': count }
verbose_images.short_description = _('Image Count')
def handle_noargs(self, **options):
mediafiles = list(MediaFile.objects.values_list("file", flat=True))
# TODO make this smarter, and take MEDIA_ROOT into account
for base, dirs, files in os.walk("media/medialibrary"):
for f in files:
full = os.path.join(base[6:], f)
if force_text(full) not in mediafiles:
self.stdout.write(os.path.join(base, f))
# ------------------------------------------------------------------------
class MediaFile(MediaFileBase):
class Meta:
app_label = "medialibrary"
@receiver(post_delete, sender=MediaFile)
def _mediafile_post_delete(sender, instance, **kwargs):
instance.delete_mediafile()
logger.info("Deleted mediafile %d (%s)" % (instance.id, instance.file.name))
# ------------------------------------------------------------------------
@six.python_2_unicode_compatible
class MediaFileTranslation(Translation(MediaFile)):
"""
Translated media file caption and description.
"""
caption = models.CharField(_("caption"), max_length=1000)
description = models.TextField(_("description"), blank=True)
class Meta:
verbose_name = _("media file translation")
verbose_name_plural = _("media file translations")
unique_together = ("parent", "language_code")
app_label = "medialibrary"
def __str__(self):
return self.caption
count = self.count_images()
return ungettext_lazy('%(count)d Image',
'%(count)d Images', count) % {'count': count }
verbose_images.short_description = _('Image Count')
class Meta:
verbose_name = _('Gallery')
verbose_name_plural = _('Galleries')
def __unicode__(self):
return self.title
class GalleryMediaFile(models.Model):
gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE)
mediafile = models.ForeignKey(MediaFile, on_delete=models.CASCADE)
ordering = models.IntegerField(default=9999)
class Meta:
verbose_name = 'Image for Gallery'
verbose_name_plural = 'Images for Gallery'
ordering = ['ordering']
def __unicode__(self):
return u'%s' %self.mediafile
class GalleryContent(models.Model):
@classmethod
def initialize_type(cls, types=DEFAULT_SPECS, **kwargs):
if 'feincms.module.medialibrary' not in settings.INSTALLED_APPS:
raise ImproperlyConfigured('You have to add \'feincms.module.'\