Answer the question
In order to leave comments, you need to log in
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
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))
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 %}
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)
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)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question