📌  相关文章
📜  image_file = models.ImageField(upload_to='images') image_url = models.URLField() - Python 代码示例

📅  最后修改于: 2022-03-11 14:46:35.085000             🧑  作者: Mango

代码示例1
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)