Django: Add Image in an Imagefield from Image Url

How to convert image url into ImageField - Django

In your view, you send a request to get the image like in this answer, and then save the received binary in the image field so you can render it later.

Django save image from url and connect with ImageField

from django.core.files import File
import os

class Item(models.Model):
image_file = models.ImageField(upload_to='images')
image_url = models.URLField()

...

def get_remote_image(self):
if self.image_url and not self.image_file:
result = urllib.urlretrieve(self.image_url)
self.image_file.save(
os.path.basename(self.image_url),
File(open(result[0]))
)
self.save()

You can override the default save() method to automatically invoke get_remote_image().

See: https://docs.djangoproject.com/en/dev/topics/db/models/#overriding-model-methods

Django loading image from url - ImageField objected has no attribute _committed

The reason you are getting

ImageField object does attribute _committed

is because the ImageField returns varchar string, not the file instances.

FileField instances are created in your database as varchar columns with a default max length of 100 characters. As with other fields, you can change the maximum length using the max_length argument. doc

For generating an empty file/image instances you can use BytesIO

Give this a try

from django.core import files
from io import BytesIO

url = "https://homepages.cae.wisc.edu/~ece533/images/airplane.png"

io = BytesIO()
io.write(requests.get(url).content)

foo = Foo()
foo.caption = payload['caption']
foo.title = payload['title']
...

extention = url.split(".")[-1]
foo.image.save(f'{str(uuid4())}.{extention}', files.File(io))

Django ImageField Uploaded to Different Path than Reported by url property?

my guess is to move

+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)  # Static returns a list of path, not a path itself.

from urls.py file of your app socialfeedia to the global urls.py file under the project package and don't forget to set the namespace socialfeedia in the corresponding urls:

from django.conf import settings
from django.urls import path, include

from django.contrib import admin

[..]

urlpatterns = [

[..]

path('socialfeedia/', include('socialfeedia.urls', namespace='socialfeedia')), # HERE

path('admin/', admin.site.urls), # Admin Area
]

# DEBUG = True
if settings.DEBUG:

from django.conf.urls.static import static

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

let me know if this helps you.

Django image saving

you can do it in the following way
I'll put the functions here, but you can put them in another file to reuse them and then import them, I'll add the necessary libraries

import PIL
from io import BytesIO
from PIL import Image
from django.core.files import File

class Image(models.Model):
image = models.FileField()

def save(self, *args, **kwargs):
new_image = self.compress_images(self.image)

# asignar la nueva imagen con menor peso
self.image = new_image
super().save(*args, **kwargs)


def valid_extension(self,_img):
if '.jpg' in _img:
return "JPEG"
elif '.jpeg' in _img:
return "JPEG"
elif '.png' in _img:
return "PNG"

def compress_images(self,image):
im = Image.open(image)
width, height = im.size
im = im.resize((width-50, height-50), PIL.Image.ANTIALIAS)
# crear a BytesIO object
im_io = BytesIO()
im.save(im_io, self.valid_extension(image.name) ,optimize=True,
quality=70)
new_image = File(im_io, name=image.name)
return new_image

Customize ImageField.image.url

You could subclass ImageField and define your own .url() method:

class JpegImageField(ImageField):
@property
def url(self):
return "/jpeg/{name}".format(name=self.name)

and use the new field class instead of regular ImageField:

class Photo(models.Model):
image = models.JpegImageField(upload_to='photo_image_files')


Related Topics



Leave a reply



Submit