Python django.db.models.fields.files.ImageFieldFile() Examples

The following are 11 code examples of django.db.models.fields.files.ImageFieldFile(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.db.models.fields.files , or try the search function .
Example #1
Source File: apps.py    From thirtylol with MIT License 6 votes vote down vote up
def init_platform(sender, **kwargs):
    platforms = (
        {'name':u'斗鱼', 'url':'http://www.douyu.com/', 'intro':u'当下最火的游戏直播平台', 'logo':'platform_logos/1.jpg'},
        {'name':u'虎牙', 'url':'http://www.huya.com/', 'intro':u'YY旗下直播网站', 'logo':'platform_logos/2.jpg'},
        {'name':u'战旗', 'url':'http://www.zhanqi.com/', 'intro':u'浙报传媒与边锋网络共同打造', 'logo':'platform_logos/3.jpg'},
        {'name':u'龙珠', 'url':'http://www.longzhu.com/', 'intro':u'腾讯旗下', 'logo':'platform_logos/4.jpg'},
        {'name':u'熊猫', 'url':'http://www.panda.tv/', 'intro':u'王思聪投资', 'logo':'platform_logos/5.jpg'},
    )
    for item in platforms:
        my_module = sender.get_model('Platform')
        try:
            p = get_object_or_404(my_module, name=item['name'])
        except Http404:
            p = my_module()
            p.name = item['name']
            p.url = item['url']
            p.introduce = item['intro']
            p.logo = ImageFieldFile(p, p.logo, item['logo'])
            p.save() 
Example #2
Source File: templated_docs_tags.py    From templated-docs with MIT License 5 votes vote down vote up
def render(self, context):
        try:
            self.value = self.value.resolve(context)
            if not isinstance(self.value, ImageFieldFile):
                raise template.VariableDoesNotExist(
                    'Image argument should be an ImageField')
            images = context.dicts[0].setdefault('ootemplate_imgs', {})

            id = len(images)
            z_index = id + 3  # Magic
            width = self.value.width * PIXEL_TO_CM
            height = self.value.height * PIXEL_TO_CM
            filename = os.path.basename(self.value.name)
            basename = os.path.splitext(filename)[0]

            images[self.value.path] = self.value
            return ('<draw:frame draw:style-name="gr%(z_index)s" '
                    'draw:name="%(basename)s" '
                    'draw:id="id%(id)s" '
                    'text:anchor-type="char" svg:width="%(width)fcm" '
                    'svg:height="%(height)fcm" draw:z-index="%(z_index)s">'
                    '<draw:image xlink:href="Pictures/%(filename)s" '
                    'xlink:type="simple" xlink:show="embed" '
                    'xlink:actuate="onLoad"/></draw:frame>') % locals()
        except template.VariableDoesNotExist:
            return '' 
Example #3
Source File: filters.py    From django-progressiveimagefield with MIT License 5 votes vote down vote up
def progressive(image_field, alt_text=''):
    """
    Used as a Jinja2 filter, this function returns a safe HTML chunk.

    Usage (in the HTML template):

        {{ obj.image|progressive }}

    :param django.db.models.fields.files.ImageFieldFile image_field: image
    :param str alt_text: str
    :return: a safe HTML template ready to be rendered
    """
    if not isinstance(image_field, ImageFieldFile):
        raise ValueError('"image_field" argument must be an ImageField.')

    for engine in engines.all():
        if isinstance(engine, BaseEngine) and hasattr(engine, 'env'):
            env = engine.env
            if isinstance(env, Environment):
                context = render_progressive_field(image_field, alt_text)
                template = env.get_template(
                    'progressiveimagefield/render_field.html'
                )
                rendered = template.render(**context)
                return Markup(rendered)
    return '' 
Example #4
Source File: test_images.py    From python-thumbnails with MIT License 5 votes vote down vote up
def test_django_image_files(self):
        from django.db.models.fields import files
        field = files.FileField()
        f = SourceFile(files.FieldFile(field=field, instance=None, name=self.FILE_PATH))
        self.assertEqual(f.file, self.FILE_PATH)
        f = SourceFile(files.ImageFieldFile(field=field, instance=None, name=self.FILE_PATH))
        self.assertEqual(f.file, self.FILE_PATH) 
Example #5
Source File: widgets.py    From iguana with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def value_from_datadict(self, data, files, name):
        value = super(CustomClearableFileInput, self).value_from_datadict(data, files, name)

        # value is false if the clear image check box is set
        if value is False:
            userModelAvatarField = get_user_model().avatar.field
            value = self.__class__.defaultAvatar = ImageFieldFile(instance=None,
                                                                  field=userModelAvatarField, name=defaultAvatar)

        return value 
Example #6
Source File: jsonserializable.py    From website with MIT License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, datetime):
            #return obj.__str__()
            return "{}-{}-{} {}:{}:{}".format(obj.year, obj.month, obj.day,obj.hour,obj.minute,obj.second)
        elif isinstance(obj,  uuid.UUID):
            return str(obj)
        elif isinstance(obj, ImageFieldFile):
            return str(obj)
        return json.JSONEncoder.default(self, obj) 
Example #7
Source File: test_admin_inline.py    From django-loci with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_add_indoor_new_location_new_floorplan(self):
        self._login_as_admin()
        p = self._get_prefix()
        params = self.params
        floorplan_file = open(self._floorplan_path, 'rb')
        params.update(
            {
                'name': 'test-add-indoor-new-location-new-floorplan',
                '{0}-0-type'.format(p): 'indoor',
                '{0}-0-location_selection'.format(p): 'new',
                '{0}-0-location'.format(p): '',
                '{0}-0-floorplan_selection'.format(p): 'new',
                '{0}-0-floorplan'.format(p): '',
                '{0}-0-floor'.format(p): '1',
                '{0}-0-image'.format(p): floorplan_file,
                '{0}-0-indoor'.format(p): '-100,100',
                '{0}-0-id'.format(p): '',
            }
        )
        r = self.client.post(reverse(self.add_url), params, follow=True)
        floorplan_file.close()
        self.assertNotContains(r, 'errors')
        loc = self.location_model.objects.get(name=params['{0}-0-name'.format(p)])
        self.assertEqual(loc.address, params['{0}-0-address'.format(p)])
        self.assertEqual(
            loc.geometry.coords, GEOSGeometry(params['{0}-0-geometry'.format(p)]).coords
        )
        self.assertEqual(loc.objectlocation_set.count(), 1)
        self.assertEqual(self.location_model.objects.count(), 1)
        self.assertEqual(self.floorplan_model.objects.count(), 1)
        ol = loc.objectlocation_set.first()
        self.assertEqual(ol.content_object.name, params['name'])
        self.assertEqual(ol.location.type, 'indoor')
        self.assertEqual(ol.floorplan.floor, 1)
        self.assertIsInstance(ol.floorplan.image, ImageFieldFile)
        self.assertEqual(ol.indoor, '-100,100') 
Example #8
Source File: orm_to_json_utils.py    From seqr with GNU Affero General Public License v3.0 4 votes vote down vote up
def _get_json_for_families(families, user=None, add_individual_guids_field=False, project_guid=None, skip_nested=False):
    """Returns a JSON representation of the given Family.

    Args:
        families (array): array of django models representing the family.
        user (object): Django User object for determining whether to include restricted/internal-only fields
        add_individual_guids_field (bool): whether to add an 'individualGuids' field. NOTE: this will require a database query.
        project_guid (boolean): An optional field to use as the projectGuid instead of querying the DB
    Returns:
        array: json objects
    """

    def _get_pedigree_image_url(pedigree_image):
        if isinstance(pedigree_image, ImageFieldFile):
            try:
                pedigree_image = pedigree_image.url
            except Exception:
                pedigree_image = None
        return os.path.join("/media/", pedigree_image) if pedigree_image else None

    def _process_result(result, family):
        result['analysedBy'] = [{
            'createdBy': {'fullName': ab.created_by.get_full_name(), 'email': ab.created_by.email, 'isStaff': ab.created_by.is_staff},
            'lastModifiedDate': ab.last_modified_date,
        } for ab in family.familyanalysedby_set.all()]
        pedigree_image = _get_pedigree_image_url(result.pop('pedigreeImage'))
        result['pedigreeImage'] = pedigree_image
        if add_individual_guids_field:
            result['individualGuids'] = [i.guid for i in family.individual_set.all()]
        if not result['displayName']:
            result['displayName'] = result['familyId']
        if result['assignedAnalyst']:
            result['assignedAnalyst'] = {
                'fullName': result['assignedAnalyst'].get_full_name(),
                'email': result['assignedAnalyst'].email,
            }
        else:
            result['assignedAnalyst'] = None

    prefetch_related_objects(families, 'assigned_analyst')
    prefetch_related_objects(families, 'familyanalysedby_set__created_by')
    if add_individual_guids_field:
        prefetch_related_objects(families, 'individual_set')

    if project_guid or not skip_nested:
        kwargs = {'nested_fields': [{'fields': ('project', 'guid'), 'value': project_guid}]}
    else:
        kwargs = {'additional_model_fields': ['project_id']}

    return _get_json_for_models(families, user=user, process_result=_process_result, **kwargs) 
Example #9
Source File: test_admin_inline.py    From django-loci with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def test_add_indoor_existing_location_new_floorplan(self):
        self._login_as_admin()
        pre_loc = self._create_location(type='indoor')
        p = self._get_prefix()
        params = self.params
        floorplan_file = open(self._floorplan_path, 'rb')
        name = 'test-add-indoor-existing-location-new-floorplan'
        params.update(
            {
                'name': name,
                '{0}-0-type'.format(p): 'indoor',
                '{0}-0-location_selection'.format(p): 'existing',
                '{0}-0-location'.format(p): pre_loc.id,
                '{0}-0-name'.format(p): pre_loc.name,
                '{0}-0-address'.format(p): pre_loc.address,
                '{0}-0-geometry'.format(p): pre_loc.geometry.geojson,
                '{0}-0-floorplan_selection'.format(p): 'new',
                '{0}-0-floorplan'.format(p): '',
                '{0}-0-floor'.format(p): '0',
                '{0}-0-image'.format(p): floorplan_file,
                '{0}-0-indoor'.format(p): '-100,100',
                '{0}-0-id'.format(p): '',
            }
        )
        r = self.client.post(reverse(self.add_url), params, follow=True)
        floorplan_file.close()
        # with open('test.html', 'w') as f:
        #     f.write(r.content.decode())
        self.assertNotContains(r, 'errors')
        loc = self.location_model.objects.get(name=params['{0}-0-name'.format(p)])
        self.assertEqual(loc.address, params['{0}-0-address'.format(p)])
        self.assertEqual(
            loc.geometry.coords, GEOSGeometry(params['{0}-0-geometry'.format(p)]).coords
        )
        self.assertEqual(loc.objectlocation_set.count(), 1)
        self.assertEqual(self.location_model.objects.count(), 1)
        self.assertEqual(self.floorplan_model.objects.count(), 1)
        ol = loc.objectlocation_set.first()
        self.assertEqual(ol.content_object.name, params['name'])
        self.assertEqual(ol.location.type, 'indoor')
        self.assertEqual(ol.floorplan.floor, 0)
        self.assertIsInstance(ol.floorplan.image, ImageFieldFile)
        self.assertEqual(ol.indoor, '-100,100') 
Example #10
Source File: test_admin_inline.py    From django-loci with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def test_add_indoor_existing_location_existing_floorplan(self):
        self._login_as_admin()
        pre_loc = self._create_location(type='indoor')
        pre_fl = self._create_floorplan(location=pre_loc, floor=2)
        p = self._get_prefix()
        params = self.params
        name = 'test-add-indoor-existing-location-new-floorplan'
        params.update(
            {
                'name': name,
                '{0}-0-type'.format(p): 'indoor',
                '{0}-0-location_selection'.format(p): 'existing',
                '{0}-0-location'.format(p): pre_loc.id,
                '{0}-0-name'.format(p): name,
                '{0}-0-address'.format(p): pre_loc.address,
                '{0}-0-location-geometry'.format(p): pre_loc.geometry,
                '{0}-0-floorplan_selection'.format(p): 'existing',
                '{0}-0-floorplan'.format(p): pre_fl.id,
                '{0}-0-floor'.format(p): 3,  # floor
                '{0}-0-image'.format(p): '',
                '{0}-0-indoor'.format(p): '-110,110',
                '{0}-0-id'.format(p): '',
            }
        )
        r = self.client.post(reverse(self.add_url), params, follow=True)
        self.assertNotContains(r, 'errors')
        loc = self.location_model.objects.get(name=name)
        self.assertEqual(loc.id, pre_loc.id)
        self.assertEqual(loc.address, params['{0}-0-address'.format(p)])
        self.assertEqual(
            loc.geometry.coords, GEOSGeometry(params['{0}-0-geometry'.format(p)]).coords
        )
        self.assertEqual(loc.objectlocation_set.count(), 1)
        self.assertEqual(self.location_model.objects.count(), 1)
        self.assertEqual(self.floorplan_model.objects.count(), 1)
        ol = loc.objectlocation_set.first()
        self.assertEqual(ol.content_object.name, params['name'])
        self.assertEqual(ol.location.type, 'indoor')
        self.assertEqual(ol.floorplan.id, pre_fl.id)
        self.assertEqual(ol.floorplan.floor, 3)
        self.assertIsInstance(ol.floorplan.image, ImageFieldFile)
        self.assertEqual(ol.indoor, '-110,110') 
Example #11
Source File: test_admin_inline.py    From django-loci with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def test_change_indoor(self):
        self._login_as_admin()
        p = self._get_prefix()
        obj = self._create_object(name='test-change-indoor')
        pre_loc = self._create_location(type='indoor')
        pre_fl = self._create_floorplan(location=pre_loc)
        ol = self._create_object_location(
            content_object=obj, location=pre_loc, floorplan=pre_fl, indoor='-100,100'
        )
        # -- ensure change form doesn't raise any exception
        r = self.client.get(reverse(self.change_url, args=[obj.pk]))
        self.assertContains(r, obj.name)
        # -- post changes
        params = self.params
        floorplan_file = open(self._floorplan_path, 'rb')
        changed_name = '{0} changed'.format(pre_loc.name)
        params.update(
            {
                'name': obj.name,
                '{0}-0-type'.format(p): 'indoor',
                '{0}-0-location_selection'.format(p): 'existing',
                '{0}-0-location'.format(p): pre_loc.id,
                '{0}-0-name'.format(p): changed_name,
                '{0}-0-address'.format(p): 'changed-address',
                '{0}-0-location-geometry'.format(p): pre_loc.geometry,
                '{0}-0-floorplan_selection'.format(p): 'existing',
                '{0}-0-floorplan'.format(p): pre_fl.id,
                '{0}-0-floor'.format(p): 3,  # floor
                '{0}-0-image'.format(p): floorplan_file,
                '{0}-0-indoor'.format(p): '-110,110',
                '{0}-0-id'.format(p): ol.id,
                '{0}-INITIAL_FORMS'.format(p): '1',
            }
        )
        r = self.client.post(
            reverse(self.change_url, args=[obj.pk]), params, follow=True
        )
        floorplan_file.close()
        self.assertNotContains(r, 'errors')
        loc = self.location_model.objects.get(name=changed_name)
        self.assertEqual(loc.id, pre_loc.id)
        self.assertEqual(loc.address, 'changed-address')
        self.assertEqual(
            loc.geometry.coords, GEOSGeometry(params['{0}-0-geometry'.format(p)]).coords
        )
        self.assertEqual(loc.objectlocation_set.count(), 1)
        self.assertEqual(self.location_model.objects.count(), 1)
        self.assertEqual(self.floorplan_model.objects.count(), 1)
        ol = loc.objectlocation_set.first()
        self.assertEqual(ol.content_object.name, params['name'])
        self.assertEqual(ol.location.type, 'indoor')
        self.assertEqual(ol.floorplan.id, pre_fl.id)
        self.assertEqual(ol.floorplan.floor, 3)
        self.assertIsInstance(ol.floorplan.image, ImageFieldFile)
        self.assertEqual(ol.indoor, '-110,110')