Python django.db.models.ImageField() Examples

The following are 30 code examples of django.db.models.ImageField(). 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 , or try the search function .
Example #1
Source File: test_ordinary_fields.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_pillow_installed(self):
        try:
            from PIL import Image  # NOQA
        except ImportError:
            pillow_installed = False
        else:
            pillow_installed = True

        class Model(models.Model):
            field = models.ImageField(upload_to='somewhere')

        field = Model._meta.get_field('field')
        errors = field.check()
        expected = [] if pillow_installed else [
            Error(
                'Cannot use ImageField because Pillow is not installed.',
                hint=('Get Pillow at https://pypi.org/project/Pillow/ '
                      'or run command "pip install Pillow".'),
                obj=field,
                id='fields.E210',
            ),
        ]
        self.assertEqual(errors, expected) 
Example #2
Source File: models.py    From fansfood with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def to_json(self):
        """
        序列模型实例,让具体的模型实例可以 json 化

        属性说明:
        a = RecodeImage.objects.get(recode_number="5+8")
        a._meta --> (<django.db.models.fields.AutoField: id>,
                    <django.db.models.fields.CharField: recode_number>,
                    <django.db.models.fields.files.ImageField: recode_image_path>,
                    <django.db.models.fields.DateTimeField: add_time>)
                    这是一个可迭代的对象,通过遍历,取得每个字段的名字(field.name)
        getattr(self, attr) -->  获取模型实例的字段值
        ImageField 字段使用 str() 字符串化
        """

        fields = []
        for field in self._meta.fields:
            fields.append(field.name)

        d = {}
        for attr in fields:
            d[attr] = str(getattr(self, attr))

        return json.dumps(d) 
Example #3
Source File: test_ordinary_fields.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_pillow_installed(self):
        try:
            from PIL import Image  # NOQA
        except ImportError:
            pillow_installed = False
        else:
            pillow_installed = True

        class Model(models.Model):
            field = models.ImageField(upload_to='somewhere')

        field = Model._meta.get_field('field')
        errors = field.check()
        expected = [] if pillow_installed else [
            Error(
                'Cannot use ImageField because Pillow is not installed.',
                hint=('Get Pillow at https://pypi.org/project/Pillow/ '
                      'or run command "pip install Pillow".'),
                obj=field,
                id='fields.E210',
            ),
        ]
        self.assertEqual(errors, expected) 
Example #4
Source File: transfer_all_images.py    From opensurfaces with MIT License 6 votes vote down vote up
def handle(self, *args, **options):
        storage = DefaultStorage()

        for model in _get_models(['shapes', 'photos', 'shapes']):
            has_images = False

            # transfer image fields
            for f in model._meta.fields:
                if isinstance(f, models.ImageField):
                    has_images = True
                    if hasattr(storage, 'transfer'):
                        filenames = model.objects.all() \
                            .values_list(f.name, flat=True)
                        print '%s: %s' % (model, f)
                        for filename in progress.bar(filenames):
                            if filename and storage.local.exists(filename):
                                storage.transfer(filename)

            # transfer thumbs
            if has_images:
                print '%s: thumbnails' % model
                ids = model.objects.all().values_list('id', flat=True)
                ct_id = ContentType.objects.get_for_model(model).id
                for id in progress.bar(ids):
                    ensure_thumbs_exist_task.delay(ct_id, id) 
Example #5
Source File: transfer_all_images.py    From opensurfaces with MIT License 6 votes vote down vote up
def handle(self, *args, **options):
        storage = DefaultStorage()

        for model in _get_models(['shapes', 'photos', 'shapes']):
            has_images = False

            # transfer image fields
            for f in model._meta.fields:
                if isinstance(f, models.ImageField):
                    has_images = True
                    if hasattr(storage, 'transfer'):
                        filenames = model.objects.all() \
                            .values_list(f.name, flat=True)
                        print '%s: %s' % (model, f)
                        for filename in progress.bar(filenames):
                            if filename and storage.local.exists(filename):
                                storage.transfer(filename)

            # transfer thumbs
            if has_images:
                print '%s: thumbnails' % model
                ids = model.objects.all().values_list('id', flat=True)
                ct_id = ContentType.objects.get_for_model(model).id
                for id in progress.bar(ids):
                    ensure_thumbs_exist_task.delay(ct_id, id) 
Example #6
Source File: models.py    From connect with MIT License 5 votes vote down vote up
def create_thumbnail(self, size=(200, 200)):
        """Generate an image thumbnail."""
        uploadfile, filename = self._resize(size=size)

        # Upload the file, set the URL to the ImageField
        self.thumbnail.save(content=uploadfile, name=filename, save=False)

        # Save the model
        self.save(process=False, update_fields=['thumbnail']) 
Example #7
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_image_field(self):
        field = models.ImageField(upload_to="foo/barness", width_field="width", height_field="height")
        name, path, args, kwargs = field.deconstruct()
        self.assertEqual(path, "django.db.models.ImageField")
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {"upload_to": "foo/barness", "width_field": "width", "height_field": "height"}) 
Example #8
Source File: images.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def get_field_attrs(self, attrs, db_field, **kwargs):
        if isinstance(db_field, models.ImageField):
            attrs['widget'] = AdminImageWidget
            attrs['form_class'] = AdminImageField
            self.include_image = True
        return attrs 
Example #9
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_image_field(self):
        field = models.ImageField(upload_to="foo/barness", width_field="width", height_field="height")
        name, path, args, kwargs = field.deconstruct()
        self.assertEqual(path, "django.db.models.ImageField")
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {"upload_to": "foo/barness", "width_field": "width", "height_field": "height"}) 
Example #10
Source File: images.py    From imoocc with GNU General Public License v2.0 5 votes vote down vote up
def get_field_attrs(self, attrs, db_field, **kwargs):
        if isinstance(db_field, models.ImageField):
            attrs['widget'] = AdminImageWidget
            attrs['form_class'] = AdminImageField
            self.include_image = True
        return attrs 
Example #11
Source File: images.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def get_field_result(self, result, field_name):
        if isinstance(result.field, models.ImageField):
            if result.value:
                img = getattr(result.obj, field_name)
                result.text = mark_safe('<a href="%s" target="_blank" title="%s" data-gallery="gallery"><img src="%s" class="field_img"/></a>' % (img.url, result.label, img.url))
                self.include_image = True
        return result

    # Media 
Example #12
Source File: images.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def get_field_attrs(self, attrs, db_field, **kwargs):
        if isinstance(db_field, models.ImageField):
            attrs['widget'] = AdminImageWidget
            attrs['form_class'] = AdminImageField
            self.include_image = True
        return attrs 
Example #13
Source File: images.py    From online with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_field_result(self, result, field_name):
        if isinstance(result.field, models.ImageField):
            if result.value:
                img = getattr(result.obj, field_name)
                result.text = mark_safe('<a href="%s" target="_blank" title="%s" data-gallery="gallery"><img src="%s" class="field_img"/></a>' % (img.url, result.label, img.url))
                self.include_image = True
        return result

    # Media 
Example #14
Source File: images.py    From online with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_field_attrs(self, attrs, db_field, **kwargs):
        if isinstance(db_field, models.ImageField):
            attrs['widget'] = AdminImageWidget
            attrs['form_class'] = AdminImageField
            self.include_image = True
        return attrs 
Example #15
Source File: tests.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_image_field(self):
        field = models.ImageField(upload_to="foo/barness", width_field="width", height_field="height")
        name, path, args, kwargs = field.deconstruct()
        self.assertEqual(path, "django.db.models.ImageField")
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {"upload_to": "foo/barness", "width_field": "width", "height_field": "height"}) 
Example #16
Source File: field.py    From django-admin-easy with MIT License 5 votes vote down vote up
def render(self, obj):
        src = helper.call_or_get(obj, self.attr)

        if isinstance(src, ModelImageField):
            src = settings.MEDIA_URL + src

        p_params = {}
        for key in self.params.keys():
            p_params[key] = helper.call_or_get(obj, self.params[key])

        p_params['src'] = src

        return '<img%s/>' % (
            flatatt(p_params)
        ) 
Example #17
Source File: images.py    From devops with MIT License 5 votes vote down vote up
def get_field_result(self, result, field_name):
        if isinstance(result.field, models.ImageField):
            if result.value:
                img = getattr(result.obj, field_name)
                result.text = mark_safe('<a href="%s" target="_blank" title="%s" data-gallery="gallery"><img src="%s" class="field_img"/></a>' % (img.url, result.label, img.url))
                self.include_image = True
        return result

    # Media 
Example #18
Source File: images.py    From devops with MIT License 5 votes vote down vote up
def get_field_attrs(self, attrs, db_field, **kwargs):
        if isinstance(db_field, models.ImageField):
            attrs['widget'] = AdminImageWidget
            attrs['form_class'] = AdminImageField
            self.include_image = True
        return attrs 
Example #19
Source File: images.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def get_field_result(self, result, field_name):
        if isinstance(result.field, models.ImageField):
            if result.value:
                img = getattr(result.obj, field_name)
                result.text = mark_safe('<a href="%s" target="_blank" title="%s" data-gallery="gallery"><img src="%s" class="field_img"/></a>' % (img.url, result.label, img.url))
                self.include_image = True
        return result

    # Media 
Example #20
Source File: images.py    From imoocc with GNU General Public License v2.0 5 votes vote down vote up
def get_field_result(self, result, field_name):
        if isinstance(result.field, models.ImageField):
            if result.value:
                img = getattr(result.obj, field_name)
                result.text = mark_safe('<a href="%s" target="_blank" title="%s" data-gallery="gallery"><img src="%s" class="field_img"/></a>' % (img.url, result.label, img.url))
                self.include_image = True
        return result

    # Media 
Example #21
Source File: test_converter.py    From graphene-django with MIT License 5 votes vote down vote up
def test_should_image_convert_string():
    assert_conversion(models.ImageField, graphene.String) 
Example #22
Source File: images.py    From Mxonline3 with Apache License 2.0 5 votes vote down vote up
def get_field_result(self, result, field_name):
        if isinstance(result.field, models.ImageField):
            if result.value:
                img = getattr(result.obj, field_name)
                result.text = mark_safe('<a href="%s" target="_blank" title="%s" data-gallery="gallery"><img src="%s" class="field_img"/></a>' % (img.url, result.label, img.url))
                self.include_image = True
        return result

    # Media 
Example #23
Source File: images.py    From Mxonline3 with Apache License 2.0 5 votes vote down vote up
def get_field_attrs(self, attrs, db_field, **kwargs):
        if isinstance(db_field, models.ImageField):
            attrs['widget'] = AdminImageWidget
            attrs['form_class'] = AdminImageField
            self.include_image = True
        return attrs 
Example #24
Source File: fields.py    From adhocracy4 with GNU Affero General Public License v3.0 5 votes vote down vote up
def formfield(self, **kwargs):
        defaults = {'form_class': forms.ImageField}
        defaults.update(kwargs)
        return super().formfield(**defaults) 
Example #25
Source File: test_metaclass.py    From django-linguist with MIT License 5 votes vote down vote up
def test_create_translation_field_has_correct_descriptor(self):
        field = create_translation_field(models.fields.CharField(), "en")
        assert field.descriptor_class == TranslationDescriptor

        field = create_translation_field(models.FileField(), "en")
        assert field.descriptor_class == files.FileTranslationDescriptor

        field = create_translation_field(models.ImageField(), "en")
        assert field.descriptor_class == files.FileTranslationDescriptor

        field = create_translation_field(models.fields.TextField(), "en")
        assert field.descriptor_class == TranslationDescriptor 
Example #26
Source File: images.py    From django_OA with GNU General Public License v3.0 5 votes vote down vote up
def get_field_result(self, result, field_name):
        if isinstance(result.field, models.ImageField):
            if result.value:
                img = getattr(result.obj, field_name)
                result.text = mark_safe('<a href="%s" target="_blank" title="%s" data-gallery="gallery"><img src="%s" class="field_img"/></a>' % (img.url, result.label, img.url))
                self.include_image = True
        return result

    # Media 
Example #27
Source File: images.py    From django_OA with GNU General Public License v3.0 5 votes vote down vote up
def get_field_attrs(self, attrs, db_field, **kwargs):
        if isinstance(db_field, models.ImageField):
            attrs['widget'] = AdminImageWidget
            attrs['form_class'] = AdminImageField
            self.include_image = True
        return attrs 
Example #28
Source File: images.py    From CTF_AWD_Platform with MIT License 5 votes vote down vote up
def get_field_result(self, result, field_name):
        if isinstance(result.field, models.ImageField):
            if result.value:
                img = getattr(result.obj, field_name)
                result.text = mark_safe('<a href="%s" target="_blank" title="%s" data-gallery="gallery"><img src="%s" class="field_img"/></a>' % (img.url, result.label, img.url))
                self.include_image = True
        return result

    # Media 
Example #29
Source File: images.py    From CTF_AWD_Platform with MIT License 5 votes vote down vote up
def get_field_attrs(self, attrs, db_field, **kwargs):
        if isinstance(db_field, models.ImageField):
            attrs['widget'] = AdminImageWidget
            attrs['form_class'] = AdminImageField
            self.include_image = True
        return attrs 
Example #30
Source File: images.py    From myblog with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_field_result(self, result, field_name):
        if isinstance(result.field, models.ImageField):
            if result.value:
                img = getattr(result.obj, field_name)
                result.text = mark_safe('<a href="%s" target="_blank" title="%s" data-gallery="gallery"><img src="%s" class="field_img"/></a>' % (img.url, result.label, img.url))
                self.include_image = True
        return result

    # Media