Django:加载夹具时,通过URL将数据添加到DB中的imageField

时间:2014-12-02 12:09:54

标签: python django django-models

我有一个夹具,它是一个json对象列表,其中一个属性是图像的url:

some_file.json:

[{"pk": 1, 
 "model": "kudisavers.product", 
 "fields": {
      "prodDesc": "Take control of your desktop. Inspire your workforce with the Dell OptiPlex 3010, designed for essential productivity, stable life cycles and simple IT control. 8 External USB 2.0 ports (2 front, 6 rear) and 2 Internal USB 2.0; 1 RJ-45; 1 VGA; 1 HDMI (optional DVI dongle); Front Panel: Mic-in, Headphone out; Back Panel: Mic-in/Line-in, Line-out; optional Parallel/Serial PCIe card (MT); optional Parallel PCIe card. Accessories - Mice : Dell Optical (Not Wireless), Scroll USB (3 buttons scroll) Black Mouse. Keyboard : US/European (QWERTY ) Dell KB212-B QuietKey USB Keyboard Black.", 
      "prodName": "Dell Optiplex 3010DT Dual Core Desktop", 
      "blockName": "Home & Tech", 
      "catUrl": "http://www.buyam.com.ng/catalog/computers-accessories/31", 
      "catName": "Computers & Accessories", 
      "prodProperties": "{u'Operating System': u'Windows 8 Pro', u'Dimensions': u'53.09 x 16.51 x 40.9cm', u'Weight': u'10kg', u'Screen size': u'18.5\" Monitor', u'Brand': u'Dell', u'Model Number': u'3010DT', u'Memory size': u'2 GB', u'Hard drive size': u'500 GB ', u'Processor type': u'Intel core i5', u'Product type': u'Desktop', u'Processor brand': u'Intel', u'Battery information': u'N/A'}", 
      "prodTypeUrl": "http://www.buyam.com.ng/catalog/laptops-and-netbooks/85", 
      "imageLink": "http://www.buyam.com.ng/images/thumb/2/a/d/TDA0220_320x350.jpg", 
      "prodUrl": "http://www.buyam.com.ng/catalog/laptops-and-netbooks/85/optiplex-3010-dt-dual-core-2-9ghz-2gb-ddr3-500gb-hdd", 
      "offerPrice": 103000.0, 
      "prodTypeName": "Laptops and Netbooks"
    }
}]

我的模型看起来像这样:

models.py

class Product(models.Model):
    blockName = models.CharField(max_length=50)
    catName = models.CharField(max_length=50)
    catUrl = models.URLField(max_length=100)
    prodTypeName = models.CharField(max_length=50)
    prodTypeUrl = models.URLField(max_length=100)
    prodName = models.CharField(max_length=50)
    prodUrl = models.URLField(max_length=100)
    prodDesc =  models.TextField(max_length=500)
    prodProperties =  models.TextField(max_length=500)
    reviews = models.TextField()
    imageLink = models.URLField(max_length=100)
    image = models.ImageField()
    offerPrice = models.FloatField()
    availability = models.NullBooleanField(null=True)

def save(self, *args, **kwargs):
    if self.imageLink:
        filename = urllib.parse(self.imageLink).path.split('/')[-1]
        img_temp = NamedTemporaryFile(delete=True)
        img_temp.write(urllib.request.urlopen(self.imageLink).read())
        img_temp.flush()
        self.image = File(img_temp)
        super(Product, self).save(*args, **kwargs)

def __str__(self):
    return self.prodName

当我通过cmd加载夹具时,我没有填充imageField。

我该如何解决这个问题? 感谢。

0 个答案:

没有答案