Create a Python image in Django without a dummy image file and test the image upload

You can test the upload even if you put the image file locally, but to complete it in the test code.

Create sample application

(python2.7, django1.6)

$ django-admin.py startproject core
$ mv core photo_book
$ cd photo_book
$ python manage.py startapp photos
$ mkdir -p static/upload  #Directory to save images

core/

settings.py


#Only additional parts
IINSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'photos',  #add to
)

MEDIA_ROOT = os.path.join(BASE_DIR, 'static/')  #add to

urls.py


from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

from photos.views import ImageCreateView

urlpatterns = patterns(
    '',
    url(r'^images/$', ImageCreateView.as_view(), name='images'),
    url(r'^admin/', include(admin.site.urls)),
)

photos/

model

models.py


from django.db import models


class Photo(models.Model):
    image = models.ImageField(upload_to='upload')

Form

forms.py


from django import forms


class PhotoForm(forms.Form):
    image = forms.ImageField()

View

views.py


from django.views.generic.edit import CreateView

from photos.models import Photo


class ImageCreateView(CreateView):
    model = Photo
    success_url = '/'

test

test.py


from StringIO import StringIO

from django.core.urlresolvers import reverse
from django.test import TestCase
from photos.models import Photo


class CreateImageTest(TestCase):
    def test_post(self):
        url = reverse("images")

        dummy_image = StringIO(
            'GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00'
            '\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;'
        )
        dummy_image.name = 'dummy_image.gif'
        dummy_image.content_type = 'image/gif'
        response = self.client.post(url, {'image': dummy_image})

        self.assertEqual(response.status_code, 302)
        #Check if it was saved in db
        self.assertEqual(Photo.objects.count(), 1)
        #Check if the saved image and the uploaded dummy image are the same
        uploaded_image = StringIO(open(Photo.objects.last().image._get_path(), 'rb').read())
        self.assertEqual(uploaded_image.getvalue(), dummy_image.getvalue())

Test run

$ python manage.py test
Creating test database for alias 'default'...
.
----------------------------------------------------------------------
Ran 1 test in 0.042s

OK
Destroying test database for alias 'default'...

reference

Recommended Posts

Create a Python image in Django without a dummy image file and test the image upload
Test & Debug Tips: Create a file of the specified size in Python
Create a Django project and application in a Python virtual environment and start the server
Create a binary file in Python
Create a local scope in Python without polluting the namespace
Create a dummy image with Python + PIL.
Write the test in a python docstring
Parse the Researchmap API in Python and automatically create a Word file for the achievement list
[GPS] Create a kml file in Python
Create a Vim + Python test environment in 1 minute
Create a GIF file using Pillow in Python
How to create a JSON file in Python
Create a MIDI file in Python using pretty_midi
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 1 ~
[Django] Implement image file upload function without using model
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 2 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 3 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 4 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 5 ~
Create a function in Python
Create a dictionary in Python
Download the file in Python
Create an exe file that works in a Windows environment without Python with PyInstaller
[GCF + Python] How to upload Excel to GCS and create a new table in BigQuery
[Django] Test to send a file by POST and check the returned context [TDD]
Create a dummy data file
Save the pystan model and results in a pickle file
[python] Change the image file name to a serial number
Change the standard output destination to a file in Python
Get the MIME type in Python and determine the file format
[Note] Import of a file in the parent directory in Python
I tried programming the chi-square test in Python and Java.
Create code that outputs "A and pretending B" in python
Create a docx file with thumbnails of photos in the folder pasted with the Python python-docx library and the free software "Reduction only."
Save the binary file in Python
Create a DI Container in Python
Create Gmail in Python without API
Create a Kubernetes Operator in Python
Create a random string in Python
Create a file uploader with Django
Create and read messagepacks in Python
Create a LINE Bot in Django
Create a temporary file with django as a zip file and return it
[Python / Django] Create a web API that responds in JSON format
Create a shell script to run the python file multiple times
Specify or create a python folder and then save the screenshot.
Create a simple scheduled batch using Docker's Python Image and parse-crontab
Read a file in Python with a relative path from the program
Create a CGH for branching a laser in Python (laser and SLM required)
Dig the directory and create a list of directory paths + file names
Get the formula in an excel file as a string in Python
Replace the directory name and the file name in the directory together with a Linux command.
Create a shortcut to run a Python file in VScode on your terminal
A memo organized by renaming the file names in the folder with python
Set up a dummy SMTP server in Python and check the operation of sending from Action Mailer
Create a simple GUI app in Python
Create a JSON object mapper in Python
Cut out A4 print in the image
[Python] Create a linebot to write a name and age on an image
Write O_SYNC file in C and Python
Run the Python interpreter in a script