Articles that enable system development with Django (Python) _Introduction

Introduction

Programming has become more familiar than before, including Python. When you challenge service development, there are various barriers.

** "I can't graduate from the introductory book or tutorial copy / paste" ** ** "I tried to make it with copy and paste, but I can't arrange it after that" ** ** "I'm not sure if the code I wrote is correct" **

By analyzing these, it can be decomposed into ** 5 factors ** as shown in the figure below.

image.png

In this article, we will focus on ** "practice phase" ** and aim to ** "develop a system that actually works" **. *** "Basic phase" ** is also organized in another article, so I will introduce the link.

(3) Basics of programming: Learning roadmap that allows you to develop and publish services from scratch with Python (4) Think about system design: Requirement definition-Articles that can be human resources who can design systems

Contents of this article

I wrote it so that you can learn ** "A series of procedures for system development using Django (Python)" ** throughout. From the overall understanding of the development process to the actual programming, the content is comprehensively learned.

The chapters are as follows.

-** What is a system in the first place? ** ** -** What is Django's MVT model? ** ** -** Django file structure ** -** Django Development Procedures_Initial Settings ** -** Django development procedure_feature addition **

After learning a series of steps, try various patterns yourself When you get used to it, please try ** original service development **.

Let's get started.

What is a "system" in the first place?

First of all, it is very important to understand the ** meaning of the word "system" **. It is introduced in the dictionary as follows.

-** System: An overall cohesiveness that organizes many things and a series of tasks **

Converting this to IT terminology,

-** System: A collection of many "data" and "programs" that organize a "series of processing" **

In other words, it is an image like "a plastic model that is completed by orderly assembling individual parts." For that purpose, three types of skills are required.

** ① Skills to think about parts necessary for development ** ** ② Skills to make individual parts ** ** ③ Skills to build in order **

Other than that, there are blind spots ** "(1) Skills to think about parts necessary for development" ** I wrote an article in "Requirements Definition-Articles that can be human resources who can design systems".

And ** "② How to make individual parts" ** has already been learned by those who have studied Python. It is enough to write a program that uses For statement / IF statement and function / class.

After that, you can develop the system by learning ** "③ Skills for orderly assembling" **. In this article, we will proceed so that you can acquire the two skills necessary for that purpose.

** (1) Understand "Overview of system development" ** ** (2) Understand the "roles of individual parts" that make up the system **

First, in order to clear (1) Let's understand ** the development method (MTV model) used by Django **.

What is Django's "MTV model"?

Django uses a technique called the ** MTV model **.

Meaning of "MTV"

MTV is an acronym for ** the three major elements that make up Django **.

You don't have to understand it exactly, so let's understand the general role.

First of all, as a premise, the system is made up of three elements: ** "screen, processing, data" **. Expressed in sentences, it looks like this.

-** After adding some "processing" to "data", display it on "screen" **

Take, for example, a system that analyzes sales data. As shown in the figure, ** "screens / processes / data" are divided into roles ** starting from user operations.

image.png

If you apply this to the MTV model, you can organize the division of roles as follows.

-** View (processing) : ** Role of central control ** - Model (data) : ** Role to control the database ** - Templage (screen) **: ** Role to control screen (web page) **

image.png

In other words, ** "screen", "processing", and "data" are linked in an orderly manner **. The system functions as a ** aggregate **.

--Definition of "system" (repost) --- ** System: A collection of many "data" and "programs" that organize a "series of processing" **

With the above, you should be able to see ** "(1) Overview of system development" **.

After that, while actually programming, while making the finished product ** Let's understand "(2) Roles of individual parts that make up the system" **.

Django file structure

First, in order to know the goal, organize the ** file structure (= parts structure) ** of the system created by Django. Let's understand ** the role played by each file ** while linking it with the MTV model.

What is especially confusing is "What is the difference between the files below **? **".

--"ʻApp_config / views.py and ʻapp_folder / views.py" --"ʻApp_config / urls.py and ʻapp_folder / urls.py"

The difference can be organized as follows, but at first I do not understand the merit of dividing.

--ʻApp_config: ** Manage the entire system ** --ʻApp_folder: ** Manage individual functions ** in the system

The first skill you need is ʻapp_folder, which is ** a skill to develop specific functions **, so Let's proceed on the premise that ʻapp_config is done by copying and ** first making a working system **.

Now let's look at the file structure.

List of files used by Django

If you proceed with development with Django, you will end up with this kind of file structure.

At this point, it's okay if you don't understand what it says, Please refer to it when you get lost in the middle of programming ** "What are you doing now?" **.


-** manage.py: A collection of functions required for development management called" management commands "** -** ʻapp_config / : Folder to store files related to global settings ** --views.py: ** [View] ** Write a program that controls the entire system --ʻUrls.py: Set the URL to use --settings.py: Manage various setting values such as DB settings -** ʻapp_folder /: Folder for storing programs implemented in the system ** --ʻAdmin.py: Management screen configuration file --views.py: ** [View] ** Describe individual functions to be implemented in the system --ʻUrls.py: File that sets the URL used in the web page --models.py: ** [Model] ** Describe the DB definition --forms.py: File that sets the input form used in the web page --migrations /: Folder where the DB definition change history remains -** templates /: [Template] Folder for storing HTML files ** --base.html`: HTML of " outer frame (sidebar, etc.) " to be displayed in common on all Web pages


Again, ** these files (= parts) play individual roles **, By properly assembling them, the whole will operate as a ** "system" **.

--Definition of "system" (repost) --- ** System: A collection of many "data" and "programs" that organize a "series of processing" **

Now, let's actually proceed with the development. Of the essential development skills mentioned at the beginning, we are dealing with ② and ③.

** ② Skills to make individual parts ** ** ③ Skills to build in order **

Django Development Procedures_Initial Settings

From here, I will write the program in Python, so I recommend that you prepare an editor.

Construction of development environment

First of all, prepare the development environment. There are four options for the development environment, but this time let's build the best "** virtual environment **" for getting started.

--PC local environment: Do nothing pip install ●● --Virtual environment: Use venv ** ⇒ Use this this time ** --Virtual Machine: Use VirtualBox --Container virtualization: use Docker

#Create a virtual environment / move folders
$ python -m venv venv
$ cd venv
#[For Windows & Command Prompt] Start virtual environment
$ Scripts/activate.bat

#[For Windows & GitBash] Starting a virtual environment
$ source Scripts/activate
* If an error occurs, "source bin"/activate」

#[For Mac] Starting a virtual environment
$ source Scripts/activate
* If an error occurs, "source bin"/activate」
#Install the library to use
$ pip install Django==2.1.5
$ pip install django-bootstrap4

#When using "MySQL" for DB, also execute the following
$ pip install mysqlclient
#Create / move development folder
$ cd ..
$ mkdir mysite
$ cd mysite

Start the project

Run start project to start developing Django. A set of configuration files required for development is automatically created.

You can use any name for ʻapp_config`, so please change it when you get used to it.

$ django-admin startproject app_config .

When the process is completed, the folder structure will be as follows.

-** ʻapp_config / : Folder to store files around the global settings ** --settings.py: A file that manages various setting values such as DB settings --ʻUrls.py: File to set the URL to use --manage.py: File that describes the functions required for system management

setting file

Now let's set up Django as a whole. It should fix LANGUAGE_CODE and TIME_ZONE at the bottom of ʻapp_config / setting.py`.

app_config/settings.py


#Language / time zone setting, etc.
LANGUAGE_CODE = 'ja'
TIME_ZONE = 'Asia/Tokyo'

Also, Django supports ** SQLite ** by default, so you can use the DB with the default settings. If you use ** MySQL **, change DATABASES in ʻapp_config / settings.py` as follows.

app_config/settings.py


#Change DATABASE as follows
DATABASES = {
    'default': {
        'ENGINE':'django.db.backends.mysql',
        'NAME':'●●(Database name)',
        'USER':'●● (DB user name)',
        'PASSWORD':'●● (DB login pass)',
        'HOST':'localhost',
        'PORT':'',
    }
}

Database preparation (migration)

Let's execute the following command at this timing. Once you've done that, you'll have the minimum database you need to develop Django.

$ python manage.py migrate

image.png

Try booting the system

Let's boot the system to make sure that the settings up to this point are successful.

$ python manage.py runserver

Then try accessing http: // localhost: 8000 from your browser. It is successful when the screen below is displayed.

image.png

If you can confirm it, press Ctrl + c (Command + c on Mac) to stop the system.

Creating application-related files

Next, we will develop specific Web application functions. Let's execute the following command.

Any name can be used for the ʻapp_folder` part.

$ python manage.py startapp app_folder

When executed, a folder named ʻapp_folder` will be created. Various files are created directly under it. * You can ignore the files not written below.

-** ʻapp_folder /: Folder for storing programs implemented in the system ** --ʻAdmin.py: File that sets the system administration screen --models.py: [Model] Describe the DB definition --views.py: [View] Write a program to run behind the system

Register the app in the configuration file

Be careful here, just create the ʻapp_folder /folder It is not recognized by ʻapp_config /, which manages the entire system.

Therefore, you need to register in ʻINSTALLED_APPS of ʻapp_config / settings.py. ʻINSTALLED_APPS` is an item for registering applications to be used in the system.

The name to be registered is made by combining three elements.

  1. The app name you specified earlier ʻapp_folder`
  2. apps
  3. Class name in ʻapp_folder / apps.py ʻAppFolderConfig

image.png

Combine these three and add "ʻapp_folder.apps.AppFolderConfig`". This will recognize the application you're about to develop inside Django.

app_config/settings.py


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app_folder.apps.AppFolderConfig', #Add this one line
]

Prepare a folder for HTML / CSS

Next, let's prepare a folder related to HTML / CSS Create folders and files in the same hierarchy as manage.py as follows.

-** templates /: [Template] Folder for storing HTML files ** - base.html - app_folder/ - top_page.html -** static /: Folder to store images, css files, javascript files ** - css/ - js/ - images/

After the creation is completed, it is OK if the following file structure is established.

image.png

Static file access settings

ʻAdd variables related to static files (such as image files) at the bottom of app_config / settings.py`. Once this setting is done, ** Inserting images into HTML files ** and ** CSS and JavaScript related work ** will be easier.

app_config/settings.py


#Added static file call settings to the bottom
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 
PROJECT_NAME = os.path.basename(BASE_DIR)
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] 
STATIC_ROOT = '/var/www/{}/static'.format(PROJECT_NAME)

Similarly, change the second line DIRS of TEMPLATES near the middle of ʻapp_config / setting.py. This will make the HTML files stored in the ** templates /` folder ** recognized on your system.

app_config/settings.py


#Add one line to TEMPLATES (template call setting)
TEMPLATES = [ 
    { 
        'BACKEND': 'django.template.backends.django.DjangoTemplates', 
        'DIRS': [os.path.join(BASE_DIR, 'templates')], #Add this line
        'APP_DIRS': True, 
        'OPTIONS': { 'context_processors': [ 
            'django.template.context_processors.debug', 
            'django.template.context_processors.request', 
            'django.contrib.auth.context_processors.auth', 
            'django.contrib.messages.context_processors.messages', 
            ], 
        }, 
    }, 
]

Media file access settings

Also add this code at the bottom of settings.py. The cases where this setting is required are as follows.

--Ability to upload ** files such as images ** -** A function to display the uploaded file as content on the Web screen ** --Ability to download ** files ** such as CSV

app_config/settings.py


#Media file settings
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

After completing the settings, create a media / folder in the same hierarchy as manage.py. The flow is to upload media files here.

image.png

Creating a base template

Next, let's create an HTML file to be displayed on the system screen. As one point, do you all know ** Bootstrap **?

** "I tried my best to study CSS, but I can't make a beautiful screen." **

** Bootstrap ** developed by Twitter is effective for solving such problems. ** You can create a stylish site without any design knowledge ** It is excellent.

Setting up to use BootStrap is very simple. Just add bootstrap4 to ʻINSTALLED_APPS in ʻapp_config / settings.py and you're good to go.

app_config/settings.py


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app_folder.apps.AppNameConfig',
    'bootstrap4', #Add this one line
]

Next, let's create an HTML file (** base template **). You can reduce the amount of code to write by ** coding the template in two types **.

-① ** "Outside" ** part common to all pages: templates / base.html -② Displayed on individual pages ** "Inside" content **: templates / app_folder / top_page.html etc.

The figure is as follows.

image.png

First, prepare a base template for ** "①Outside" **. I made a design that can withstand a certain amount of use, so please copy it and use it as it is.

In addition, in the part of ** "↓↓ content body ↓↓" ** at the bottom, The HTML file that is the content of ** "② Inside" ** is reflected.

template/base.html


<!DOCTYPE html>

{% load bootstrap4 %}
{% bootstrap_css %}
{% bootstrap_javascript jquery='slim' %}
{% load static %}

<html lang="ja">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" type='text/css' href="{% static 'css/style.css'%}">
    <link rel="stylesheet" href="https://cccabinet.jpn.org/bootstrap4/css/style.css">
    <title>Django development sample</title>

    {% block extra_css %}{% endblock %}

</head>

  <body>
    <!--↓ ↓ Top navigation bar ↓ ↓-->
    <div class="container-fluid">
      <div class="row">
        <div class="col-12">
          <nav class="navbar navbar-expand-lg fixed-top navbar-dark bs-navbar" style='background-color:cadetblue;' id="bs-navbar">
            <a class="navbar-brand mr-md-2" href="/app_folder/top_page">
Sample development screen
            </a>
              <!--↓ ↓ Dummy for adjusting the layout ↓ ↓-->
              <ul class="navbar-nav mr-auto">
                <li class="nav-item"><a class="nav-link" href="#">   </a></li>
                <li class="nav-item"><a class="nav-link" href="#">   </a></li>
              </ul>
              <!--↑↑ Dummy up to here ↑↑-->                            

              <ul class="navbar-nav">
                <li class="nav-item"><a class="nav-link" href="/#" >Sample 1</a></li>
                <li class="nav-item"><a class="nav-link" href="/#" >Sample 2</a></li>
                <li class="nav-item"><a class="nav-link" href="/#" >Sample 3</a></li>
                <li class="nav-item"><a class="nav-link" href="/accounts/login" >Login</a></li>
                <li class="nav-item"><a class="nav-link" href="/accounts/logout" >Log out</a></li>
              </ul>
            </div>
          </nav>
        </div>
      </div>
    </div>


    <!--"Sidebar" and "content body part"-->
    <div id="content" class="container-fluid">
      <div class="row flex-xl-nowrap">

        <!--↓ ↓ Sidebar ↓ ↓-->
        <div id="sidemenu" class="col-2 d-none d-md-block bg-light sidebar align-self-start">
          <div class="sidebar-sticky">
            <ul class="nav flex-column">

              <li class="nav-item">
                <nav class="navbar navbar-light bg-light">
                  <a class="navbar-brand" href="/#">
                    <span data-feather=""></span>Top page
                  </a>
                </nav>
              </li>
              <li class="nav-item">
                <nav class="navbar navbar-light bg-light">
                  <a class='navbar-brand' href='/#'>
                    <span data-feather=""></span>Sidebar 1
                  </a>
                </nav>
              </li>
              <li class="nav-item">
                <nav class="navbar navbar-light bg-light">
                  <a class='navbar-brand' href='/#'>
                    <span data-feather=""></span>Sidebar 2
                  </a>
                </nav>
              </li>         
              <li class="nav-item">
                <nav class="navbar navbar-light bg-light">
                  <a class='navbar-brand' href='/#'>
                    <span data-feather=""></span>Sidebar 3
                  </a>
                </nav>
              </li>         
              <li class="nav-item">
                <nav class="navbar navbar-light bg-light">
                  <a class='navbar-brand' href='/#'>
                    <span data-feather=""></span>Sidebar 4
                  </a>
                </nav>
              </li>         
              <li class="nav-item">
                <nav class="navbar navbar-light bg-light">
                  <a class='navbar-brand' href='/#'>
                    <span data-feather=""></span>Sidebar 5
                  </a>
                </nav>
              </li>         
            </ul>
          </div>
        </div id="sidemenu">
        <!--↑↑ Sidebar up to here ↑↑-->

        <!--↓ ↓ Content body ↓ ↓-->
        <div class="col-10">
          {% block contents %}
          {% endblock %}
        </div>
        <!--↑↑ Content body up to here ↑↑-->
      </div>
    </div>
    </div>
  </body>
</html>

<!--Icon used for sidebar-->
<!--List of available icons: https://voyager-jp.com/blog/javascript/feather/ -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/feather-icons/4.9.0/feather.min.js"></script>
<script>feather.replace()</script>

Creating each template

After creating the base template, create an HTML file that will be ** "inside" content **. We will add content later, so first copy the following and create a file.

templates/app_folder/top_page.html


{% extends 'base.html' %}
{% block contents %}

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center mt-5 border-bottom">
    <h1 class="h2">top page</h1>
</div>

<div>
    <h4>Describe the content here</h4>
</div>

{% endblock %}

There is only one point, and there are three {% ~%} described at the beginning and end. It is a mechanism that you can insert ** "" inside "content part" ** into the base template.

This completes the template preparation.

Nothing can be displayed on the screen just by creating a Template (HTML file), so Next, let's create a View that controls the inside of the system.

Create a View that controls the inside of the system

As I mentioned at the beginning, there are two types of View.

--ʻApp_config / views.py: ** Control the whole ** roughly ** --ʻApp_folder / views.py: ** Control individual functions **

First, create ʻapp_config / views.pyfrom the simplest one. Createviews.py in the ʻapp_config folder and describe the contents as follows.

app_config/views.py


from django.shortcuts import render, redirect, reverse  
from django.views import View  
  
class index(View):
    def get(self, request, *args, **kwargs):
        return redirect(reverse('app_folder:top_page'))
index = index.as_view()

This is a setting such as ** "If there is access to the system, skip to the top page" **. It's okay if you write the same every time.

Then open ʻapp_folder / views.py to control the specific functions of the system and copy the following This is writing a function that "displays top_page.html` when the top page is accessed ".

app_folder/views.py


from django.shortcuts import render  
from django.views import View  
  
class SampleView(View):  
	def get(self, request, *args, **kwargs):  
		return render(request, 'app_folder/top_page.html')
top_page = SampleView.as_view()

Now that we have created the minimum view, let's move on.

Creating a URL dispatcher

Here, set the URL required to access the system from the web screen. For example, http: // localhost: 8000 / my_app / top_page, you can freely decide the followinghttps: //.

There are two types of files to change.

--ʻApp_config / urls.py: System-wide URL design --ʻApp_folder / urls.py: URL design in individual apps

The relationship between the two affects the order in which the URLs are constructed. ** http: // localhost: 8000 / <URL setting of app_config / urls.py> / <URL setting of app_folder / urls.py> ** URLs are constructed in this order.

First is ʻapp_config / urls.py`.

app_config/urls.py


from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from . import views

#Overall URL design
urlpatterns = [
    #The app "app" to be created this time_URL to access "folder"
    path('app_folder/', include('app_folder.urls')),
    #If you do not specify any URL (app_config/views.With py, "app" automatically_(Already set to access "folder")
    path('', views.index, name='index'),
    #URL to access the management site
    path('admin/', admin.site.urls),
]

#URL setting for publishing media files
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Next, create ʻurls.py in the ʻapp_folder / folder and write as follows.

Since only the top page (top_page /) is prepared yet, ʻurlpatterns` is one line, The number of URLs to be registered will increase as various functions are added.

app_folder/urls.py


from django.urls import path
from . import views

app_name = 'app_folder'
urlpatterns = [
    path('top_page/', views.top_page, name='top_page')
]

As a matter to understand, ** http: // localhost: 8000 / <URL setting of app_config / urls.py> / <URL setting of app_folder / urls.py> **

According to the URL setting rules here, the URL to access the top page is http://localhost:8000/app_folder/top_page And so on. This is how the URL dispatcher works.

Try booting the system

Now that you have a complete set of settings, let's boot the system.

$ python manage.py runserver

If there is no problem, the terminal will be displayed as below.

image.png

Next, start your browser and access http: // localhost: 8000 / app_folder / top_page.

If the following screen is displayed, it is successful, and in the part temporarily entered with sample characters You can create various services by ** adding content by yourself **.

image.png

Now that the initial setup is complete, let's add just one simple feature.

Django Development Procedures_Develop Additional Features

Receive the search condition ** from the ** input form displayed on the web screen, ** Recall the data stored in the database ** Let's develop additional features.

The processing flow is as follows.

--Display the input form on the screen --Receive the search criteria entered by the user --Retrieve information from the database based on search conditions --Display the retrieved information on the screen

Database construction

First, let's define a database to store the data.

In order to understand models.py, ** knowledge of the database is also required **, so After studying this article, I recommend that you study in detail with some Django Primer.

app_folder/models.py


from django.db import models

class SampleDB(models.Model):
    class Meta:
        db_table = 'sample_table' #Table name used in DB
        verbose_name_plural = 'sample_table' #Table name to display on Admion site
    sample1 = models.IntegerField('sample1', null=True, blank=True) #Store numbers
    sample2 = models.CharField('sample2', max_length=255, null=True, blank=True) #Store string

Then execute the following command to reflect the settings in the DB.

$ python manage.py makemigrations
$ python manage.py migrate

If it looks like this in the terminal, it is successful.

image.png

Administrator user registration

After setting up the database, let's register the user who manages the system. First, enter the following command.

$ python manage.py createsuperuser

Next, the questions will be asked in the following order, so enter them in order. For security reasons, the password will not be displayed when you type it, but it's okay. (I'm surprised at first, but don't worry)

After inputting, if Superuser created successfully. is displayed, the administrator user registration is successful.

Management site construction

After registering as an administrator, let's create a ** management site **.

What is a management site?

--Originally, you need to remember ** MySQL ** etc. to operate DB ――You can't do MySQL even though Python (Django) is full. .. --You, ** Let's operate the DB on the screen from the management site **!

It is a convenient website, so let's experience how to operate the DB first rather than understanding it in words. Make the settings to create a management site at once.

app_folder/admin.py


from django.contrib import admin
from .models import SampleDB # models.Class name specified by py

admin.site.register(SampleDB) # models.Class name specified by py

This completes the management site settings. Let's access localhost: 8000 / admin after running the following command.

$ python manage.py runserver

image.png

After logging in with the user name and password you created earlier If you see a screen like this, you are successful.

image.png

Let's try registering in the database. Registration is completed in 3 steps.

-①: Click Samplle_table

image.png

-②: Click `Add SAMPLE_DB``

image.png

--③: Fill in the items and click "Save"

image.png

This completes the registration in the database.

image.png

View / template changes

Now that you have registered the information in the database, let's get the data. After that, proceed with the flow of displaying the data on the Web screen.

--Receive search conditions from the input form on the screen --Get data from DB based on search conditions --Pass the acquired data to the template (screen)

** [Receive search conditions from the input form on the screen] ** First, create page01.html to create an input form.

templates/app_folder/page01.html


{% extends 'base.html' %}
{% block contents %}

<h4 class="mt-5 mb-4 border-bottom">Enter search conditions</h4>
<form  action="{% url 'app_folder:top_page' %}" method="post">
<div class="container-fluid">
  <div class="row">
    <div class="col-2">
      <input class="form-control" type="text" name="input_data" maxlength="255">
    </div>
    <div class="col-2">
      <div class="text-left align-bottom">
          <button type="submit" name="button" class="btn btn-info">
Search
          </button>
      </div>
    </div>
  </div>
</div>
{% csrf_token %}
</form>

{% endblock %}

** [Obtain data from DB based on search conditions] ** Then edit views.py to receive the data from the input form

app_folder/views.py


from django.shortcuts import render  
from django.views import View  
from .models import SampleDB

class SampleView(View):  
	def get(self, request, *args, **kwargs):  
		return render(request, 'app_folder/page01.html')

	def post(self, request, *args, **kwargs):  
		input_data = request.POST['input_data']
		result = SampleDB.objects.filter(sample1=input_data)
		result_sample1 = result[0].sample1
		result_sample2 = result[0].sample2
		context={'result_sample1':result_sample1, 'result_sample2':result_sample2}
		return render(request, 'app_folder/page02.html', context=context,)
		
top_page = SampleView.as_view()

** [Pass the acquired data to the template (screen)] ** And finally, create a new page02.html to display the data obtained from the DB.

templates/app_folder/page02.html


{% extends 'base.html' %}
{% block contents %}

<h4 class="mt-5 mb-4 border-bottom">Display DB search results</h4>
<div class="container-fluid">
  <div class="row">
    <div class="col-4">
      <p>sample1:{{result_sample1}}</p>
      <p>sample2:{{result_sample2}}</p>
    </div>
  </div>
</div>

{% endblock %}

Operation check

Once this is done, boot the system again Go to http: // localhost: 8000 / app_folder / top_page /.

$ python manage.py runserver

If you get a screen like this, it's working.

image.png

After entering ** "1" ** in the input form and clicking the search button If the ** "1st sample" ** registered in the database earlier is displayed, it is successful.

image.png

This completes the Django initial setup and simple feature addition steps. ** This set of files will be the basis for Django development **, so save it and save it.

at the end

In this article, after organizing the five issues in system development, I dealt with (1) and (2) with figures.

(1) The whole picture of system development is not visible (2) The roles of the individual parts that make up the system are not visible. (3) I don't have the basics to challenge development (4) I don't have the skills to think about system design from ideas (5) What to make? (Idea) does not come out

Then, after organizing the ** system definition **, I think that I was able to actually understand ② and ③ out of the three required skills through programming.

** System: A collection of many "data" and "programs" that organize a "series of processing" **

Required skills: ① Skills to think about the parts necessary for development ② Skills to make individual parts ③ Skills to build up in an orderly manner

In addition, since I wrote it with a policy of ** "Make something that works first" **, there are some parts where the explanation is omitted. If you don't understand something, please use the introductory book or tutorial you have at hand to make up for it.

We hope that everyone who reads the article will develop a good service. Until the end Thank you for reading.

As the title suggests, this article was written as ** "Introduction" **, so please look forward to the sequel.

【P.S.】 We also publish various information on SNS, so if you feel good reading the article I would be grateful if you could follow Twitter account "Saku731".

Recommended Posts

Articles that enable system development with Django (Python) _Introduction
[Python] Build a Django development environment with Docker
Django 1.11 started with Python3.6
Development digest with Django
Do Django with CodeStar (Python3.6.8, Django2.2.9)
Introduction to Python Django (2) Win
Do Django with CodeStar (Python3.8, Django2.1.15)
Python3 + Django ~ Mac ~ with Apache
Getting Started with Python Django (1)
Getting Started with Python Django (4)
Getting Started with Python Django (3)
Getting Started with Python Django (6)
Getting Started with Python Django (5)
[Python] Articles that enable sparse matrix calculations at high speed
Test Driven Development with Django Part 3
Test Driven Development with Django Part 4
IPynb scoring system made with TA of Introduction to Programming (Python)
Test Driven Development with Django Part 6
Enable Python raw_input with Sublime Text 3
Hadoop introduction and MapReduce with Python
Othello game development made with Python
Make a recommender system with python
IOS application development with Python (kivy) that even monkeys can do
Prepare Python development environment with Atom
Test Driven Development with Django Part 1
Introduction to Python Django (2) Mac Edition
Test Driven Development with Django Part 5
[Introduction to Python3 Day 21] Chapter 10 System (10.1 to 10.5)
System trading starting with Python3: long-term investment
[Python] A program that creates stairs with #
[Development environment] Python with Xcode [With screen transition]
Introduction to Python Image Inflating Image inflating with ImageDataGenerator
"System trade starting with Python3" reading memo
Easy introduction of speech recognition with Python
[Introduction to Python] Let's use foreach with Python
CentOS 6.4 with Python 2.7.3 with Apache with mod_wsgi and Django
Application development using SQLite with Django (PTVS)
Visualize point P that works with Python
A typed world that begins with Python
Python local development environment construction template [Flask / Django / Jupyter with Docker + VS Code]
[Python] Easy introduction to machine learning with python (SVM)
Introduction to Artificial Intelligence with Python 1 "Genetic Algorithm-Theory-"
Markov Chain Chatbot with Python + Janome (1) Introduction to Janome
Project cannot be created with Python3.5 (Windows) + django1.7.1
Create test data like that with Python (Part 1)
Build Django + NGINX + PostgreSQL development environment with Docker
Build the fastest Django development environment with docker-compose
Introduction to Artificial Intelligence with Python 2 "Genetic Algorithm-Practice-"
Create an app that guesses students with python
Build Python development environment with Visual Studio Code
Introduction to Tornado (1): Python web framework started with Tornado
[Web development with Python] query is also redirect
Create a page that loads infinitely with python
Django with Python Tools 2.2 for Visual Studio (PTVS 2.2)
Introduction to formation flight with Tello edu (Python)
Build a Django development environment with Doker Toolbox
Introduction to Python with Atom (on the way)
Explosive speed with Python (Bottle)! Web API development
A simple to-do list created with Python + Django
Introduction to Generalized Linear Models (GLM) with Python
What Python beginners got hooked on with Django