S
S
sportik1742020-12-12 09:35:07
Django
sportik174, 2020-12-12 09:35:07

How to save image in ImageField by url?

There is an image available for example at this url ' google.com/image.png '
There is an ImageField in the Product model

How do I load an image into this ImageField so that I can then display it in the template?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sportik174, 2020-12-16
@sportik174

I upload an image using the Wget library for Python
And in the Imagefield I write the value of the filename variable

import wget
import os

directory = '../uploads'
url = collection_img
filename = wget.download(url)
os.rename(filename,os.path.join(directory,filename))

D
Dmitry, 2020-12-12
@pyHammer

sportik174 if the image is stored remotely, and there is no urgent need to download it, then I usually do this. I don't use ImageField, but I use CharField (or TextField in case of very long URL), I call it image_url for example. Next, I store the entire URL in a field.
You can display an image in a template like this

{% load thumbnail %}

{% thumbnail object.image_url "200x200" as im %}
    <img src="{{ im.url }}">
{% endthumbnail %}

for this you need to install sorl-thumbnail .
As an alternative to object.image_url, you can do something like this if you need to get a file object from the model
from django.db import models
from sorl.thumbnail import get_thumbnail

class Product(models.Model):
    image_url = ...

    @property 
    def image(self):
        return get_thumbnail(self.image_url, '200x200', crop='center', quality=75)

But here you need to take into account that you need to transfer the image geometry.
All this will be saved in the cache, and at any time it can be reset, and the next time you request an image in the template, it will be downloaded from the specified URL.
If you need to have the remote image on your server as a copy, then simply download the image, for example, using requests , save it to a file on the server in the MEDIA_ROOT folder, cut off everything up to MEDIA_ROOT, including MEDIA_ROOT itself, and save part of the path in the ImageField in the field.
For example, /home/project/project/media/images/image.jpg is the full path, and only images/image.jpg (or /images/image.jpg, I don't remember exactly) need to be saved in the ImageField.
PS
For the Product model, it's better to do this:
class Product(models.Model):
    image = models.ForeignKey(ProductImage, on_delete=models.SET_NULL,
                                                  related_name='+', blank=True, null=True)

class ProductImage(models.Model):
    image_url = ...
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images', null=True)

In this case, you can save many images for one product, as well as have one main photo for the product.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question