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

The following are 11 code examples of django.db.models.fields.files.FieldFile(). 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: serializers.py    From django-spillway with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_fields(self):
        fields = super(RasterModelSerializer, self).get_fields()
        if not self.Meta.raster_field:
            for name, field in fields.items():
                if isinstance(field, serializers.FileField):
                    self.Meta.raster_field = name
                    break
        fieldname = self.Meta.raster_field
        request = self.context.get('request')
        renderer = getattr(request, 'accepted_renderer', None)
        try:
            obj = self.instance[0]
        except (IndexError, TypeError):
            obj = self.instance
        modelfield = getattr(obj, fieldname, None)
        if (isinstance(renderer, BaseGDALRenderer)
                or not isinstance(modelfield, FieldFile)):
            fields[fieldname] = serializers.ReadOnlyField()
        return fields 
Example #2
Source File: fields.py    From django-GDPR with MIT License 6 votes vote down vote up
def get_encrypted_value(self, value: FieldFile, encryption_key: str):
        file_name = value.name
        value.delete(save=False)
        file = self.get_replacement_file()

        if func_supports_parameter(value.storage.save, 'max_length'):
            value.name = value.storage.save(file_name, file, max_length=value.field.max_length)
        else:
            #  Backwards compatibility removed in Django 1.10
            value.name = value.storage.save(file_name, file)
        setattr(value.instance, value.field.name, value.name)

        value._size = file.size  # Django 1.8 + 1.9
        value._committed = True
        file.close()

        return value 
Example #3
Source File: rest_generic_test_cases.py    From django-is-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_serialized_data(self, request, resource, update=False):
        inst = self.new_instance(resource.model)

        form_class = resource(request)._generate_form_class(inst=update and inst or None)
        form = form_class(initial={'_user': self.logged_user.user, '_request': None}, instance=inst)
        data = {}

        for field in form:
            if not isinstance(field, ReadonlyBoundField):
                value = field.value()
                if isinstance(value, FieldFile):
                    value = None
                data[field.name] = value

        # Removed instance (must be created because FK)
        inst.delete()

        return data, inst 
Example #4
Source File: test_case.py    From djangoSIGE with MIT License 5 votes vote down vote up
def replace_none_values_in_dictionary(dictionary):
    for key, value in dictionary.items():
        if value is None or isinstance(value, FieldFile):
            dictionary[key] = '' 
Example #5
Source File: test_templatetags.py    From python-thumbnails with MIT License 5 votes vote down vote up
def test_get_thumbnail_templatetag_with_FileField_as_source(self, mock_get_thumbnail):
        field = files.FileField()
        _file = files.FieldFile(field=field, instance=None, name='image.jpg')
        Template(
            '{% load thumbnails %}'
            '{% get_thumbnail image "200x200" as im %}'
            '{{im.url}}',
        ).render(Context({
            'image': _file
        }))

        mock_get_thumbnail.assert_called_once_with(_file, '200x200') 
Example #6
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 #7
Source File: fields.py    From zing with GNU General Public License v3.0 5 votes vote down vote up
def _get_realpath(self):
        """Return realpath resolving symlinks if necessary."""
        if not hasattr(self, "_realpath"):
            # Django's db.models.fields.files.FieldFile raises ValueError if
            # if the file field has no name - and tests "if self" to check
            if self:
                self._realpath = os.path.realpath(self.path)
            else:
                self._realpath = ""
        return self._realpath 
Example #8
Source File: test_models.py    From django-spillway with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        name = self.f.name.replace('%s/' % default_storage.location, '')
        ff = FieldFile(None, RasterStore._meta.get_field('image'), name)
        self.data = {'image': ff} 
Example #9
Source File: files.py    From django-linguist with MIT License 5 votes vote down vote up
def __get__(self, instance, instance_type=None):
        file_value = result = super(FileTranslationDescriptor, self).__get__(
            instance, instance_type=instance_type
        )

        # If this value is a string (instance.file = "path/to/file") or None
        # then we simply wrap it with the appropriate attribute class according
        # to the file field. [This is FieldFile for FileFields and
        # ImageFieldFile for ImageFields; it's also conceivable that user
        # subclasses might also want to subclass the attribute class]. This
        # object understands how to convert a path to a file, and also how to
        # handle None.
        if isinstance(file_value, str) or file_value is None:
            result = self.field.attr_class(instance, self.field, file_value)

        # Other types of files may be assigned as well, but they need to have
        # the FieldFile interface added to them. Thus, we wrap any other type of
        # File inside a FieldFile (well, the field's attr_class, which is
        # usually FieldFile).
        elif isinstance(file_value, File) and not isinstance(file_value, FieldFile):
            result = self.field.attr_class(instance, self.field, file_value.name)
            result.file = file_value
            result._committed = False

        # Finally, because of the (some would say boneheaded) way pickle works,
        # the underlying FieldFile might not actually itself have an associated
        # file. So we need to reset the details of the FieldFile in those cases.
        elif isinstance(file_value, FieldFile) and not hasattr(file_value, "field"):
            result.field = self.field
            result.storage = self.field.storage

        result.instance = instance

        super(FileTranslationDescriptor, self).__set__(instance, result)

        return result 
Example #10
Source File: widgets.py    From django-is-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render(self, name, value, attrs=None, renderer=None):
        attrs = attrs or {}
        output = ['<div class="drag-and-drop-wrapper">']
        output.append('<div class="drag-and-drop-placeholder"%s></div>' % (id and 'data-for="%s"' % id or ''))
        output.append('<div class="thumbnail-wrapper">')
        if value and isinstance(value, FieldFile):
            output.append(self._render_value(value))
        output.append('</div><div class=file-input-wrapper>')
        output.append(super(DragAndDropFileInput, self).render(name, value, attrs=attrs))
        output.append(2 * '</div>')
        return mark_safe('\n'.join(output)) 
Example #11
Source File: widgets.py    From django-is-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _render_readonly(self, name, value, attrs=None, renderer=None, request=None, form=None, initial_value=None):
        if value and isinstance(value, FieldFile):
            return format_html('<a href="{}">{}</a>', value.url, os.path.basename(value.name))
        else:
            return super()._render_readonly(name, value, attrs, renderer, request, form, initial_value)