Download a remote image and save it to a Django model

后端 未结 6 915
醉话见心
醉话见心 2020-12-01 01:52

I am writing a Django app which will fetch all images of particular URL and save them in the database.

But I am not getting on how to use ImageField in Django.

6条回答
  •  隐瞒了意图╮
    2020-12-01 02:30

    Try doing it this way instead of assigning path to the image...

        import urllib2
        from django.core.files.temp import NamedTemporaryFile
        def handle_upload_url_file(url):
            img_temp = NamedTemporaryFile()
            opener = urllib2.build_opener()
            opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20120427 Firefox/15.0a1')]
            img_temp.write(opener.open(url).read())
            img_temp.flush()
            return img_temp
    

    use the above function like this..

        new_image = images_data()
        #rest of the data in new_image and then do this.
        new_image.image.save(slug_filename,File(handle_upload_url_file(url)))
        #here slug_filename is just filename that you want to save the file with.
    

提交回复
热议问题