[PYTHON] Django beginners create simple apps 1

Introduction

It's been a year and a half since I started learning Django. Finally, I was able to make a simple web application (modoki) with my own hands, so I will record it after reviewing it. We hope that you will share the little knowledge that the eternal beginner Programmer has gained and help those who are stumbling on the first move.

Purpose

We'll strip away the complexity and hassle as much as possible, create a simplified web app, and specialize in learning how Django works. So don't test, don't use CSS, or deploy like Django Tutorial # 5. The so-called front end is set aside for the time being. Only understand what is connected and how it moves around the back end. Implement CRUD (Create, Read, Update, Delete) and if it works, you will reach the goal. (Please don't ask me if it's a web application even though I can't connect to the internet.)

Target

People who have completed the Django tutorials and Django Girls, but don't seem to know what's going on, and think it's impossible to create a web app on their own.

Series table of contents for beginners to create simple apps

-Django Beginners Create Easy Apps 1 --Preparation-Overview of Django-Creating models.py -Django beginners make simple apps 2 --Implementation of Read part (creation of urls.py, views.py, template file) -Django beginners make simple apps 3 --Implementation of Create part (creation of form.py etc.) --Django Beginners make simple apps 4 --Comparison of Class-based-view and Function-view --Django Beginners make simple apps 5 (Completed) --Implementation of Update part and Delete part

environment

The big picture of Django

It's often said that "Django is a web application framework that uses Python," but it doesn't come to mind. From what I understand, what is a web application? When asked, "What is the information (or data) extracted from the DB (database) and displayed", then what is the framework? When asked, "a tool box packed with various tools to make the work (extracting and displaying information) easier" is answered.

What you're doing inside Django

If you imagine what Django is doing internally, it looks like the figure below. I take out the information from the box full of information and post it on the bulletin board.

IMG_0354.jpg
  1. models.py: Make a container for information
  2. urls.py: Decide where to display the information (which bulletin board to put it on)
  3. views.py: Decide how to collect and process information
  4. Template: Decide how to paste the information

If you create or change the above four files in order, it will work at least.

0. Get ready (up to the rocket launch page)

If you've done the tutorial, you should be able to get Django working. The links below are for your reference.

Procedures for developing Django with VSCode

1. Get ready (complete the whole setup)

After displaying the rocket launch page, enter the command to create an application from the virtual environment. The name of this app is myapp

(myenv)$ python manage.py startapp myapp

Then modify config / setting.py

--Added myapp to INSTALLED_APPS IMG_0358.jpg

--Added [os.path.join (BASE_DIR,'templates')], to TEMPLATES IMG_0359.jpg

--Fixed LANGUAGE to ja --Corrected TIME_ZONE to ʻAsia / Tokyo` --Added STATICFILES_DIRS = [os.path.join (BASE_DIR,'static'),] IMG_0360.jpg

--Create templates directory in the same hierarchy as manage.py --Create static directory in the same hierarchy as manage.py

It should have the following directory structure and file structure (excerpts of only the main ones).

.
├── config    #I used config as a reference to "Django's textbook basics that can be used in the field"
│   ├── settings.py
│   ├── urls.py
├── db.sqlite3
├── myenv
│   ├── bin
│   ├── include
├── manage.py
├── myapp
│   ├── admin.py
│   ├── apps.py
│   ├── forms.py
│   ├── migrations
│   ├── models.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── static        #The location of the static directory and templates directory depends on the tutorial
└── templates        #It may be different, but manage.It seems that the same hierarchy as py is good

This completes all the preparation stages.

2. Design

When you set a goal. The web application that is created is "Movie Viewing Record". A list of the movies I watched appears in the list, and when I click the title, the impression of the movie comes out. A very simple version of a Yahoo movie. Goal if you can implement this CRUD (Create, Read, Update, Delete). If you don't set this goal, there is no end to what you can do when you start sticking to it, and when you start pursuing difficult functions, beautiful appearance, and usability, you will be overwhelmed by the distance of the goal. The following is a vague image of the finished product.

136231D5-13EE-474C-9135-D306B8C5A305.jpeg

It would be nice if the following functions could be implemented in this.

  1. A movie viewing list appears (Read)
  2. Click the title to display the details screen (Read)
  3. Enter the movie title, movie director, viewing date, and impression (Create)
  4. Correct the impression you entered (Update)
  5. The movie was so terrible that I erased the information and decided not to watch it (delete)

First of all, I want to start making a box to put information = making a model.

3. Create models.py

I wrote earlier that making a model is "making a box to put information in", but in other words, "making a table". An image of making several small tables and "linking" them to make a large list. This time, we will create a table called Movie, a table called Director, and a table called Log. The source code is as follows.

myapp/models.py



from django.db import models #Bring tools to make a table
from django.utils import timezone #Bring tools to handle time


class Director(models.Model): #Make a table called Director
    name = models.CharField(max_length=100, verbose_name="directed by") #nameというfieldに文字列でdirected by名を入れる宣言
    def __str__(self): #The following two lines are functions for displaying the director's name when entering data using the management site.
        return self.name


class Movie(models.Model): #Make a table called Movie
    title = models.CharField(max_length=100, verbose_name="title")
    watch_date = models.DateField() #I brought a tool called timezone, so I can enter date data
    director = models.ForeignKey(Director, on_delete=models.CASCADE, verbose_name="directed by", related_name='movie')
    def __str__(self):            #Declaration that the field called director will be linked from the "table called Director"
        return self.title         #related_The name will be explained in detail in another time.


class Log(models.Model): #Create a table called Log
    text = models.TextField() #Declaration that the field called text is a place to enter a lot of strings
    movie = models.ForeignKey(Movie, on_delete=models.CASCADE, verbose_name="title", related_name='log')
    def __str__(self):            #Declaration that the field called movie will be linked from the "table called Movie"
        return self.text          #self.It is displayed with the contents entered when entering data using the management site with text

Imagine that you can create something like the figure below with the above source code. B594169D-3FD9-4CB6-ACD9-756DDE66F7D2.jpeg

When models.py is created, this is a blueprint, so actually reflect it in the database

(myenv) $ python manage.py makemigrations
(myenv) $ python manage.py migrate

The table is complete, but there is no content (data). You can enter the data from python manage.py shell, but it's easier and easier to imagine if you enter the data from the admin site. Register model in admin.py to use the admin site

myapp/admin.py



from django.contrib import admin
from myapp.models import Director, Movie, Log    #Add this part

admin.site.register(Director)    #Maybe there is a way to register all at once
admin.site.register(Movie)       #I would appreciate it if someone could teach me
admin.site.register(Log)

Set up superuser to use the admin site

(myenv) $ python manage.py createsuperuser
#Set user name, email address, password, etc.

Enter some data from the admin site (127.0.0.1:8000/admin) F4284CE1-80D6-42AD-8935-8E8DA27B2C54.jpeg

Now that models.py is complete and the data is entered, the first stage is complete. Next time, I will explain where to display in urls.py, how to retrieve information in views.py, how to create a Template and display that information.

Summary

--Django makes it easier for you to retrieve and display the information stored in the database. --First, create models.py to store information --A model is a table, and think about what kind of items to display, what type of data to put, and how to associate.

Continue to next time Django beginners create simple apps 2

Recommended Posts

Django beginners create simple apps 1
Django beginners create simple apps 2
Django beginners create simple apps 5
Django beginners make simple apps 4
Create initial settings and staff apps in Django
Create a Django schedule
django oscar simple tutorial
Create Django Todo list
Create an API with Django
Create a (simple) REST server
Create ToDo List [Python Django]
Create a homepage with django
Shell to create django project
Create a Django login screen
Create your own Django middleware
Create a simple textlint server
Create and list Django models
(For beginners) Try creating a simple web API with Django
Hello World (beginners) on Django
Create a social integration API for smartphone apps with Django
Rails users try to create a simple blog engine with Django
Steps to create a Django project
Django beginners tried building an environment
[For beginners] Django -Development environment construction-
Create new application use python, django
[Django] Create your own 403, 404, 500 error pages
Create a file uploader with Django
Create a LINE Bot in Django