I have a Photo model that looks like this
class Photo(models.Model):
title = models.CharField(max_length=100, blank=True)
width = models.IntegerField()
height = models.IntegerField()
image = models.ImageField(upload_to=upload_to_callable, widt开发者_StackOverflowh_field="width", height_field="height")
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey()
create_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
site = models.ForeignKey(Site)
In one of my tests I need to create this model programmatically. This is what I am doing
def _create_random_image(self):
import Image,ImageDraw
img = Image.new("RGB", (300,300), "#FFFFFF")
draw = ImageDraw.Draw(img)
r,g,b = rint (0,255), rint(0,255), rint(0,255)
dr = (rint(0,255) - r)/300.
dg = (rint(0,255) - g)/300.
db = (rint(0,255) - b)/300.
for i in range(300):
r,g,b = r+dr, g+dg, b+db
draw.line((i,0,i,300), fill=(int(r),int(g),int(b)))
tmpfilename = "/tmp/test36052.png"
img.save(tmpfilename, "PNG")
f = file(tmpfilename)
return f
def testHomePageImage(self):
tmpfile = self._create_random_image()
photo = Photo.objects.create(image=tmpfile,
title=site1_home_page.title,
site=self.site1,
content_object = site1_home_page)
I get the following error
AttributeError: 'file' object has no attribute 'width'
Is there an internal django object that extends the file object that I can use?
Try returning ImageFile(f)
instead of f
directly. ImageFile
is in django.core.files.images.ImageFile
. Off of the top of my head, I think that'll do it.
Edit: Corrected typo so it's correct.
精彩评论