我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用django.db.models.ImageField()。
def result_item(self, item, obj, field_name, row): opts = obj._meta try: f = opts.get_field(field_name) except models.FieldDoesNotExist: f = None if f: if isinstance(f, models.ImageField): img = getattr(obj, field_name) if img: db_value = str(img) if db_value.startswith('/'): file_path = urlparse.urljoin(settings.REMOTE_MEDIA_URL, db_value) else: file_path = img.url if type(self.list_gallery)==str: file_path = '%s%s'%(file_path,self.list_gallery) item.text = mark_safe('<a href="%s" target="_blank" data-gallery="gallery"><img src="%s" class="field_img"/></a>' % (file_path, file_path)) return item # Media
def get_image_field(verbose_name, max_length=250): "Try to use FileBrowseField, with ImageField as fallback" try: from filebrowser.fields import FileBrowseField return FileBrowseField( verbose_name, max_length=max_length, directory='flatpages', extensions=['.jpg', '.png'], blank=True, null=True, ) except: return models.ImageField( verbose_name, max_length=max_length, upload_to='flatpages/', blank=True, null=True, )
def __get_list_image(self): """ :return: the ImageField to use for thumbnails in lists NB note that the Image Field is returned, not the ICEkit Image model as with get_hero_image (since the override is just a field and we don't need alt text), not Image record. """ list_image = first_of( self, 'list_image', 'get_hero_image', 'image', ) # return the `image` attribute (being the ImageField of the Image # model) if there is one. return getattr(list_image, "image", list_image)
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
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
def test_should_image_convert_string(): assert_conversion(models.ImageField, graphene.String)
def get_field_result(self, result, field_name): if isinstance(result.field, models.ImageField): if result.value: img = getattr(result.obj, field_name) db_value = str(img) if db_value.startswith('/'): file_path = urlparse.urljoin(settings.REMOTE_MEDIA_URL, db_value) else: file_path = img.url result.text = mark_safe('<a href="%s" target="_blank" title="%s" data-gallery="gallery"><img src="%s" class="field_img"/></a>' % (file_path, result.label, file_path)) self.include_image = True return result # Media
def __init__(self, *args, **kwargs): super(ImageAdmin, self).__init__(*args, **kwargs) self.formfield_overrides.update({models.ImageField: {'widget': AdminImageWidget}})
def get_media_path(self, filename): """ Returns path (relative to MEDIA_ROOT/MEDIA_URL) to directory for storing page-scope files. This allows multiple pages to contain files with identical names without namespace issues. Plugins such as Picture can use this method to initialise the 'upload_to' parameter for File-based fields. For example: image = models.ImageField( _("image"), upload_to=CMSPlugin.get_media_path) where CMSPlugin.get_media_path calls self.page.get_media_path This location can be customised using the CMS_PAGE_MEDIA_PATH setting """ return join(get_cms_setting('PAGE_MEDIA_PATH'), "%d" % self.pk, filename)
def formfield(self, **kwargs): defaults = {'form_class': forms.ImageField} defaults.update(kwargs) return super().formfield(**defaults)
def test_get_concrete_class_for_model_field(self): """ The get_concrete_class_for_model_field method should return the correct OmniField subclass """ self.assertEqual(OmniField.get_concrete_class_for_model_field(models.CharField()), OmniCharField) self.assertEqual(OmniField.get_concrete_class_for_model_field(models.NullBooleanField()), OmniBooleanField) self.assertEqual(OmniField.get_concrete_class_for_model_field(models.BooleanField()), OmniBooleanField) self.assertEqual(OmniField.get_concrete_class_for_model_field(models.DateTimeField()), OmniDateTimeField) self.assertEqual(OmniField.get_concrete_class_for_model_field(models.DecimalField()), OmniDecimalField) self.assertEqual(OmniField.get_concrete_class_for_model_field(models.EmailField()), OmniEmailField) self.assertEqual(OmniField.get_concrete_class_for_model_field(models.FloatField()), OmniFloatField) self.assertEqual(OmniField.get_concrete_class_for_model_field(models.IntegerField()), OmniIntegerField) self.assertEqual(OmniField.get_concrete_class_for_model_field(models.BigIntegerField()), OmniIntegerField) self.assertEqual(OmniField.get_concrete_class_for_model_field(models.PositiveIntegerField()), OmniIntegerField) self.assertEqual(OmniField.get_concrete_class_for_model_field(models.SmallIntegerField()), OmniIntegerField) self.assertEqual(OmniField.get_concrete_class_for_model_field(models.TimeField()), OmniTimeField) self.assertEqual(OmniField.get_concrete_class_for_model_field(models.URLField()), OmniUrlField) self.assertEqual(OmniField.get_concrete_class_for_model_field(models.SlugField()), OmniSlugField) self.assertEqual(OmniField.get_concrete_class_for_model_field(models.FileField()), OmniFileField) self.assertEqual(OmniField.get_concrete_class_for_model_field(models.ImageField()), OmniImageField) self.assertEqual(OmniField.get_concrete_class_for_model_field(models.DurationField()), OmniDurationField) self.assertEqual( OmniField.get_concrete_class_for_model_field(models.GenericIPAddressField()), OmniGenericIPAddressField ) self.assertEqual( OmniField.get_concrete_class_for_model_field(models.CommaSeparatedIntegerField()), OmniCharField ) self.assertEqual( OmniField.get_concrete_class_for_model_field(models.PositiveSmallIntegerField()), OmniIntegerField ) self.assertEqual( OmniField.get_concrete_class_for_model_field(models.ForeignKey(DummyModel2)), OmniForeignKeyField ) self.assertEqual( OmniField.get_concrete_class_for_model_field(models.ManyToManyField(DummyModel2)), OmniManyToManyField )
def test_field_class(self): """ The model should define the correct field class """ self.assertEqual(OmniImageField.FIELD_CLASS, 'django.forms.ImageField')
def get_concrete_class_for_model_field(cls, model_field): """ Method for getting a concrete model class to represent the type of form field required :param model_field: Model Field instance :return: OmniField subclass """ field_mapping = { models.CharField: OmniCharField, models.TextField: OmniCharField, models.BooleanField: OmniBooleanField, models.NullBooleanField: OmniBooleanField, models.DateField: OmniDateField, models.DateTimeField: OmniDateTimeField, models.DecimalField: OmniDecimalField, models.EmailField: OmniEmailField, models.FloatField: OmniFloatField, models.IntegerField: OmniIntegerField, models.BigIntegerField: OmniIntegerField, models.PositiveIntegerField: OmniIntegerField, models.PositiveSmallIntegerField: OmniIntegerField, models.SmallIntegerField: OmniIntegerField, models.CommaSeparatedIntegerField: OmniCharField, models.TimeField: OmniTimeField, models.URLField: OmniUrlField, models.ForeignKey: OmniForeignKeyField, models.ManyToManyField: OmniManyToManyField, models.SlugField: OmniSlugField, models.FileField: OmniFileField, models.ImageField: OmniImageField, models.DurationField: OmniDurationField, models.GenericIPAddressField: OmniGenericIPAddressField } field_mapping.update(cls.get_custom_field_mapping()) return field_mapping.get(model_field.__class__)
def resize_image(self, save=True): # original code for this method came from # http://snipt.net/danfreak/generate-thumbnails-in-django-with-pil/ # If there is no image associated with this. # do not create thumbnail if not self.file: return requested_width = self.width # Set our max thumbnail size in a tuple (max width, max height) NEW_SIZE = (self.width, 9999) # Open original photo which we want to thumbnail using PIL's Image image = PIL.Image.open(self.file.file) if requested_width > image.size[0]: # We don't want to upscale images, record a lower width instead self.width = image.size[0] else: # Convert to RGB if necessary # Thanks to Limodou on DjangoSnippets.org # http://www.djangosnippets.org/snippets/20/ # # I commented this part since it messes up my png files # # if image.mode not in ('L', 'RGB'): # image = image.convert('RGB') # We use our PIL Image object to create the thumbnail, # which already has a thumbnail() convenience method that # contrains proportions. # Additionally, we use Image.ANTIALIAS to make the image look # better. Without antialiasing the image pattern # artifacts may result. image.thumbnail(NEW_SIZE, PIL.Image.ANTIALIAS) # Save the resized image (or original) temp_handle = BytesIO() image.save(temp_handle, image.format, quality=90) temp_handle.seek(0) # Save image to a SimpleUploadedFile which can be saved into # ImageField suf = SimpleUploadedFile( os.path.split(self.file.name)[-1], temp_handle.read(), content_type=PIL.Image.MIME[image.format]) # Save SimpleUploadedFile into image field extension = suf.name.rsplit('.', 1)[-1] self.hash = self.get_hash(suf) self.file.save( name='{}.{}'.format(self.hash, extension), content=suf, save=False)