[PYTHON] Generate and post dummy image data with Django

Introduction

I'm just studying Django from Udemy and playing with it, so I'm improving the TODO app of Udemy's Django course and the in-house SNS, so I think that the level is the same. [Thorough commentary! ] Master the basics of Django and create 3 apps!

Therefore, I am doing it with the idea of making something that moves completely out of sight, such as practicality. I think there are many points that are difficult to understand in the first article, but I would appreciate it if you could watch over with warm eyes.

Thing you want to do

When registering image data in Django, it was very troublesome to type in the data one by one, select the image, and so on, so I was wondering if there was any good way.

$ python manage.py runscript <file name>

I learned that python files can be executed with, so I decided to use this. I won't go into details about runscript, but this will execute the run method of any file in the scripts directory in the directory where manage.py is located. Since I created a file called add_dummies.py here, add_dummies.py will be included in .

Image generation

Since it was troublesome to select an image, I decided to generate an image by referring to the following article. Create a dummy image with Python + PIL.

The code I actually used to generate it is below. The only place I arranged is that the color and size of the image are changed with random numbers so that the image can be identified at a glance.

add_dummyies.py


from PIL import Image,ImageDraw, ImageFont
import random
colors = [(255,0,0), (0,255,0), (0,0,255),(0,0,0),(255,255,255)]#List of red, green, blue, black and white colors

def make_image(N):
    """
Create image file
The return value is the name of the file
    """
    screen = (200+random.randint(0,100), 200+random.randint(0,100))
    pen_color=random.choice(colors)
    bg_color=random.choice(colors)
    img = Image.new('RGB', screen, bg_color)
    x, y = img.size
    u = x - 1
    v = y - 1
    draw = ImageDraw.Draw(img)
    draw.line((0, 0, u, 0), pen_color)
    draw.line((0, 0, u, v), pen_color)
    draw.line((0, 0, 0, v), pen_color)
    draw.line((u, 0, 0, v), pen_color)
    draw.line((u, 0, u, v), pen_color)
    draw.line((0, v, u, v), pen_color)
    filename="/sample_{}.jpg ".format(N)
    img.save("media"+filename)
    return filename

This will generate any n image files and save the images in the location ./media/<image file> as seen from the directory where manage.py resides.

In addition, the model of this app is defined as follows.

models.py


from django.db import models

class RecommendedBook(models.Model):
    author = models.CharField(max_length=100)
    bookTitle = models.CharField(max_length=50)
    content = models.TextField()
    bookImage=models.ImageField(upload_to="")
    genre = models.CharField(max_length=200, null=True, blank=True, default="")
    good = models.IntegerField(null=True, blank=True,default=0)
    goodtext = models.CharField(max_length=500,null=True,blank=True, default="")
    notGood = models.IntegerField(null=True, blank=True,default=0)
    notGoodtext = models.CharField(max_length=500,null=True,blank=True, default="")

I used the Faker function because I wanted to save other elements as well, but I will omit that because it is not the subject of this time. Add the following run method to add_dummies.py to execute it. Now that we have to add other elements as well:

add_dummies.py



from book.models import RecommendedBook
import random,string
from faker import Faker
fakegen=Faker("ja_JP")

genres=["Technical book","English","Math","novel","Impressed","pleasant"]#Set the genre to an appropriate list and randomly retrieve it later

fakegen = Faker()

def run():
    N=5#Create about 5 data
    for entry in range(N):
        imgfile=make_image(entry)
        bookGenre=random.choice(genres)+" "+random.choice(genres)#Set about two genres
        dummy=RecommendedBook(author=fakegen.name(), bookTitle=fakegen.word(),
                              content=fakegen.text(), genre=bookGenre,
                              bookImage=imgfile
                              )
        dummy.save()

When you run it and look into the management screen

スクリーンショット 2020-05-02 17.38.52.png

The new data was saved successfully!

the end

That's it! ~~ I did some research on my own, but I couldn't find a good method, so it turned out to be such a muddy method. ~~ I would like to introduce the upward compatibility of this article below. Create a dummy image file in Python without a dummy image file in Django and test the image upload

Also, since it is relatively slow to register data because it is rotated in a for loop, it does not matter much if the number of loops is small, but if it increases to a certain extent, it will take a considerable amount of time. I thought it was a problem. I would be grateful if you could teach me, "There is a way to make it easier!" "This will make it faster!" For the time being, I will put the github page where the code of this article is located.

Thank you for reading until the end!

Recommended Posts

Generate and post dummy image data with Django
POST the image with json and receive it with flask
Save tweet data with Django
HTTPS with Django and Let's Encrypt
Automatically generate model relationships with Django
Generate fake table data with GAN
Data pipeline construction with Python and Luigi
Create a dummy image with Python + PIL.
Generate Japanese test data with Python faker
Put your own image data in Deep Learning and play with it
POST variously with Python and receive with Flask
CRUD POST with Nuxt & Django REST Framework
Let's make an image recognition model with your own data and play!
CentOS 6.4 with Python 2.7.3 with Apache with mod_wsgi and Django
Divide data into project-like units with Django (2)
Send and receive image data as JSON over the network with Python
Try to generate an image with aliasing
Ramen map creation with Scrapy and Django
Create a Python image in Django without a dummy image file and test the image upload
Build a data analysis environment that links GitHub authentication and Django with JupyterHub
How to automatically generate API document with Django REST framework & POST from document screen
Image characters and post to slack (python slackbot)
Divide your data into project-like units with Django (3)
Django: Record User Agent and manage with Admin
Implement "Data Visualization Design # 3" with pandas and matplotlib
Interactively visualize data with TreasureData, Pandas and Jupyter.
Divide your data into project-like units with Django
Data cleansing 3 Use of OpenCV and preprocessing of image data
Post an article with an image to WordPress with Python
Display the image after Data Augmentation with Pytorch
Develop a web API that returns data stored in DB with Django and SQLite
Internationalization with django
CRUD with Django
I just wanted to extract the data of the desired date and time with Django
Notes on HDR and RAW image processing with Python
Relationship data learning with numpy and NetworkX (spectral clustering)
Create dummy data using Python's NumPy and Faker packages
Deep learning image analysis starting with Kaggle and Keras
Generate a vertical image of a novel from text data
Image capture / OpenCV speed comparison with and without GPU
Overview and tips of seaborn with statistical data visualization
Story of image analysis of PDF file and data extraction
[PyTorch Tutorial ⑦] Visualizing Models, Data, And Training With Tensorboard
Get comments and subscribers with the YouTube Data API
Challenge image classification with TensorFlow2 + Keras 3 ~ Visualize MNIST data ~
Dynamically create tables in schema with Django, dynamically generate models
Investigate Java and python data exchange with Apache Arrow
Generate Fibonacci numbers with Python closures, iterators, and generators
Sort post data in reverse order with Django's ListView
POST the image selected on the website with multipart / form-data and save it to Amazon S3! !!
Return the image data with Flask of Python and draw it to the canvas element of HTML
I automatically collected my Qiita post data with Raspberry Pi and notified it regularly with Slack