Skip to content

Instantly share code, notes, and snippets.

@qingfeng
Created May 16, 2010 14:23
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save qingfeng/402903 to your computer and use it in GitHub Desktop.
Save qingfeng/402903 to your computer and use it in GitHub Desktop.
Django Image Field UnitTest
from django.db import models
class M1(models.Model):
title = models.CharField(max_length=100)
img1 = models.ImageField(upload_to="static/")
def __unicode__(self):
return self.title
"""
This file demonstrates two different styles of tests (one doctest and one
unittest). These will both pass when you run "manage.py test".
Replace these with more appropriate tests for your application.
"""
from django.test import TestCase
from django.core.files import File
from app1.models import M1
class SimpleTest(TestCase):
def test_basic_addition(self):
m1 = M1()
m1.title = "aaa"
m1.img1 = File(open("/tmp/p5/twitter.jpg"))
m1.save()
p = M1.objects.get(id=1).img1.path
self.failUnless(open(p), 'file not found')
@littleq0903
Copy link

awesome, it helps me a lot. Thanks

@carpincho
Copy link

thanks!

@lemonprogis
Copy link

thanks for this!

Is there a way to clean up the files afterwards?

@pmutua
Copy link

pmutua commented Feb 1, 2019

I'm getting, UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

@alexshchegretsov
Copy link

alexshchegretsov commented Jun 17, 2019

Same thing, UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
Solved:
open file in binary mode >>> open("file/file_2/here.jpg", "rb")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment