将CSV列中的图像下载到Django ImageField

时间:2017-05-15 12:57:57

标签: python django csv django-models django-rest-framework

由于我在django中使用ImageField模型,我需要将这些图像保存到数据库,以及相应的标题和说明。

response.content返回图像的二进制blob,ImageField需要一个有效的图像,我只是在这里遇到障碍。

这是我的样本csv数据

title   description     image
Item 1  Description 1   http://www.imgur.com/784/77987987.jpg
Item 2  Description 2   http://www.image.com/images/797-oijio.jpg
Item 3  Description 3   https://www.google.com/logo.jpg

这是我的图像模型,

class Image(BaseModel):
    title = models.CharField(max_length=200, unique=True)
    description = models.CharField(max_length=400, null=True, blank=True)
    image = models.ImageField(null=True, blank=True)

    class Meta:
        db_table = 'images'
    def __str__(self):
        return self.title




import csv
import validators
from django.core.management.base import BaseCommand
import requests
from images.models import Image

def get_image_content(url):
    resp = requests.get(url)
    if resp.status_code == 200:
        return resp.content

class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument('filepath'),

    def handle(self, **options):
        csv_path = options["filepath"]
        with open(csv_path) as f:
            data = list(csv.DictReader(f))

        images = []
        for row in data:
            if validators.url(row['image']):
                img, _ = Image.objects.get_or_create(title=row['title'])
                img.description = row['description']
                # download image, populate filename and img_raw_data variables
                img.image.save(filename, img_raw_data, save=True)
                img.save()

1 个答案:

答案 0 :(得分:1)

你可以做到

import urllib
from urlparse import urlparse
from django.core.files import File

#code
result = urllib.urlretrieve(row['image'])
filename = urlparse(row['image']).path.split('/')[-1]

img.image.save(
        filename,
        File(open(result[0]))
        )
img.save()