50👍
✅
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
14👍
from django.db import models
from django.core.files import File
from urllib.request import urlopen
from tempfile import NamedTemporaryFile
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:
img_temp = NamedTemporaryFile(delete=True)
img_temp.write(urlopen(self.image_url).read())
img_temp.flush()
self.image_file.save(f"image_{self.pk}", File(img_temp))
self.save()
This solution avoid any utf-8 errors received during url process.
It works only with python 3.6+ because the f string.
Check this link: https://twigstechtips.blogspot.com/2012/04/django-programmatically-saving-image.html
- [Django]-Favorite Django Tips & Features?
- [Django]-Django Query using .order_by() and .latest()
- [Django]-How to use subquery in django?
10👍
For python3
from django.core.files import File
from urllib import request
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 = request.urlretrieve(self.image_url)
self.image_file.save(
os.path.basename(self.image_url),
File(open(result[0], 'rb'))
)
self.save()
- [Django]-Get Primary Key after Saving a ModelForm in Django
- [Django]-What is the best way to upload files in a modern browser
- [Django]-Storing an Integer Array in a Django Database
7👍
Python3
from django.db import models
from django.core.files import File
from urllib.request import urlopen
from tempfile import NamedTemporaryFile
class Item(models.Model):
image_file = models.ImageField(upload_to='images')
image_url = models.URLField()
def save(self, *args, **kwargs):
if self.image_url and not self.image_file:
img_temp = NamedTemporaryFile(delete=True)
img_temp.write(urlopen(self.image_url).read())
img_temp.flush()
self.image_file.save(f"image_{self.pk}", File(img_temp))
super(Item, self).save(*args, **kwargs)
It`s similar but with automated save ‘image_file’, when add ‘image_url’
- [Django]-Exception: You cannot access body after reading from request's data stream
- [Django]-Django – set user permissions when user is automatically created using get_or_create
- [Django]-<Django object > is not JSON serializable
Source:stackexchange.com