Python Django Tutorial (1)

This is a material for study sessions. I will explain while following the tutorial of django1.8. https://docs.djangoproject.com/en/1.8/intro/tutorial01/

Since version 1.4 is the latest version of the official Japanese document, there are some differences, but the general flow is the same, so it's a good idea to read it. http://django-docs-ja.readthedocs.org/en/latest/intro/tutorial01.html

In the explanation of the official website, the project name is mysite, We will create it as a tutorial project.

Addendum (2015/11/18): Tutorial Tutorial has been created. → Tutorial Summary

environment

OS:Mac OSX10.11 python:3.4.2 django:1.8.5

Source code

Put the tutorial source code on github. Please refer to it as we will tag the important points and commit as finely as possible. https://github.com/usa-mimi/tutorial

file organization

We will proceed with this file structure.

tutorial/  #Directory created when cloned with git
    ├ .git/
    ├ .gitignore
    ├ ...
    └ tutorial/  #The explanation will be explained here as root unless otherwise noted.
          ├ manage.py  #Specify when executing django commands
          ├ ...
          └ tutorial/
                ├ ...
                ├ urls.py  #project URL
                └ settings.py  #project configuration file

The top tutorial directory is the target of git. This is done to put files that are not related to django itself, such as README for git and settings for deploy.

In this directory (tutorial) $ django-admin startproject tutorial When you run this command The files and directories under tutorial / tutorial are automatically generated.

The state where the project_start tag is attached with git is the state immediately after executing the above command.

From here, unless otherwise noted, the explanation will be based on tutorial / tutorial </ b>.

Description of the automatically created file

https://docs.djangoproject.com/en/1.8/intro/tutorial01/#creating-a-project

./manage.py This file is specified when performing various operations on the command line. When starting the server, migrating the DB, executing the self-made command, etc., pass the command to this file and execute it.

$ python manage.py runserver $ python manage.py migrate It is like this.

Since manage.py has execute permission You can also write $ ./manage.py instead of $ python manage.py.

If no arguments are passed, a list of commands that can be executed will be displayed. If you want to know more details, please refer to the official website. https://docs.djangoproject.com/en/1.8/ref/django-admin/

If you run it and get the following output, django is not installed. Create a virtual environment and install django, or use the workon command to enter the virtual environment.

$ ./manage.py
Traceback (most recent call last):
  File "./manage.py", line 8, in <module>
    from django.core.management import execute_from_command_line
ImportError: No module named django.core.management

tutorial/settings.py This is the project setting file. Apps and middleware to enable, Set various settings such as DB connection settings and various directories.

If you want to know the setting items in detail, please refer to the official website. https://docs.djangoproject.com/en/1.8/topics/settings/

tutorial/urls.py This is the URL setting of the server. Look at the requested URL and write in this file which view (described later) to return the response. It is specified as ROOT_URLCONF in settings.py.

Official explanation → https://docs.djangoproject.com/en/1.8/topics/http/urls/

Creating a database

Documents → https://docs.djangoproject.com/en/1.8/intro/tutorial01/#database-setup Source → project_start tag

Database settings

Let's follow the tutorial and create a database next. Which DB to use is described in the configuration file (tutorial / settings.py). Open the configuration file and look around line 77.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

By default, sqlite3 is used for the above, in the same directory as manage.py. You are supposed to use a DB file named db.sqlite3. In the case of sqlite engine, NAME is the path to the sqlite file. BASE_DIR points to the directory where manage.py is located. ʻOs.path.join` is a function that joins paths with a separator according to the system.

If you want to use mysql server or postgresql server, please rewrite this file as follows.

#mysql server
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydatabase',
        'USER': 'mydatabaseuser',
        'PASSWORD': 'mypassword',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}
#postgresql server
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'mydatabase',
        'USER': 'mydatabaseuser',
        'PASSWORD': 'mypassword',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}

Supplement: sqlite

sqlite is a simple database that manages the database as a file. It is very suitable for prototyping because it is not necessary to prepare a server and you can easily delete the database just by deleting the files. However, access is slower than a normal DB server, and it tends to cause trouble when accessing at the same time. Use mysql or postgresql to run the completed program. In the case of mac, it is installed by default, but in the case of windows, it seems that you need to install it manually.

Please refer to the URL of the installation reference site. http://www.dbonline.jp/sqliteinstall/install/index1.html

Database creation

After setting the database, let's actually create the database (add a table). The command to create a database is migrate. $ ./manage.py migrate

If you use mysql or postgresql, you may need to prepare an empty database in advance. Don't think about anything when using sqlite3. When you execute the command, a file will be created.

If you execute the command without touching the settings, a table will be created to save the user information and session information used for authentication.

$ ./manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: messages, staticfiles
  Apply all migrations: contenttypes, auth, sessions, admin
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying sessions.0001_initial... OK

Supplement: syncdb

Until django 1.6, the database was initialized using the command syncdb. When this command is executed, the migrate command and the createsuperuser command described below are executed. It will be a movement that will be executed continuously. As of django1.8, the command remains and can be executed, but it has been officially deprecated since django1.7.

Please note that the Japanese documentation is django 1.4 and is explained in syncdb.

Server startup confirmation

Documents → https://docs.djangoproject.com/en/1.8/intro/tutorial01/#the-development-server Source → project_start tag

Check with browser

The django framework also has a server function, so you don't need to prepare a dedicated server during development. The command to execute is runserver. When executed, the development server will start using port 8000 by default. In this state, you can check the operation by accessing http: // localhost: 8000 / with a browser.

$ ./manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
October 31, 2015 - 08:55:38
Django version 1.8.5, using settings 'tutorial.settings'
Starting development server at http://127.0.0.1:8000/  #← Address at startup
Quit the server with CONTROL-C.
[31/Oct/2015 09:06:54] "GET / HTTP/1.1" 200 1767  #← Displayed when accessed with a browser

Kobito.uICdzG.png The default screen is displayed because nothing has been created.

If you want to change the port number Give the port number as an argument, such as $ ./manage.py runserver 8080. If you want to access from a PC in the same LAN If you write something like $ ./manage.py runserver 0.0.0.0:8000 You will be able to access from within the same LAN. Check the IP of the machine with commands such as ʻipconfig and ʻifconfig.

Supplement: Automatic loading of runserver

If you change the program while running on runserver, django will restart automatically. You don't have to bring the terminal that is running server, stop it, and start it. However, if you add a new template directory, it may not be loaded automatically, so be careful.

Add app

Documents → https://docs.djangoproject.com/en/1.8/intro/tutorial01/#creating-models Source → start_project tag → ʻadd_app_4_database_migration` tag

We will finally add applications. The tutorial uses a voting app called polls as an example to explain how to create a model.

Before that, I will explain the flow of using the application with django.

  1. Add an application with $ ./manage.py startapp appname.

  2. Describe the model (database table) used in the application in ʻappname / models.py`.

  3. Add the created app to project / settings.py

  4. Database update

  5. Describe the model display and operation (addition, editing, etc.) in ʻappname / views.py`. The html to be used is also prepared here.

  6. Describe ʻappname / urls.py` and associate url and views

  7. Read ʻappname / urls.py from project / urls.py`.

1 to 4 will be done in this tutorial. 5 and later will be explained in Tutorial 3. (Tutorial 2 is about the "management screen") The source tag is attached in the format of ʻadd_app_x`.

1. Add polls app

Execute the startapp command of manage.py. A directory with the app name and some files will be created automatically.

$ ./manage.py startapp polls
$ tree polls
polls
├── __init__.py
├── admin.py  #Files related to the management site
├── migrations  #It's automatically generated so don't touch it
│   └── __init__.py
├── models.py  #File that describes table information and operations
├── tests.py  #Edit this file if you want to write a test
└── views.py  #Add functions that receive requests and return responses

In Tutorial 3, add forms.py,templates /, ʻurls.py` manually in addition to this.

2. Model description

Let's rewrite polls / models.py following the tutorial. The class created by inheriting the models.Model class is a class that represents a DB table. The properties set using the models. ~ Field instance represent the columns of the table. The property name becomes the column name of the table as it is. In the tutorial, the Question table and the Choice table are set.

polls/models.py



from django.db import models


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')


class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

Supplement: Model

Although it does not appear in this tutorial, you can adjust the behavior of the class in various ways by setting the Meta class. Documents → https://docs.djangoproject.com/en/1.8/ref/models/options/

You can specify the default order when acquiring data, and change the name of the created table.

By default, a table of ʻappname_modelnameis created. In the tutorial example, a table ofpolls_question and polls_choice` is created. We do not recommend changing the table name unless you have a specific reason.

Other useful settings include renaming on the admin page described in the next tutorial, and Setting unique constraints for multiple fields (for example, limiting by date and item).

The description method is as follows

class Question(models.Model):
    class Meta:
        app_label = 'polls'
        verbose_name = 'Question'
        table_name = 'polls_question'

Supplement: Field

Please refer to the original document for what kind of field there is. Documents → https://docs.djangoproject.com/en/1.8/ref/models/fields/#field-types

The equivalent of a general DB column type should be covered. In addition to some common options, field has field-specific options and required items. For example, CharField represents a general DB char type. Since the char type requires the number of characters to be specified, django's CharField also requires the max_length argument.

ForeignKey is a slightly special field that expresses a relationship to another model. The column type will be the same type as the primary key of the model with the relation attached, and the column name will be the property name with _id added. In the tutorial example, an integer type column named question_id is created. (Because the default primary key is integer type)

The class is passed directly as an argument because of the relation to the model defined in the same file. If you want to paste the relation to the model defined in another file, specify the model to put the relation with the character string in the format of ʻapp.model. Example: question = models.ForeignKey ('polls.Question')`

3. Add application

Documents → https://docs.djangoproject.com/en/1.8/intro/tutorial01/#activating-models

Simply adding an app with startapp will not activate that application. There is an item in the list of apps to use in tutorial / settings.py, so let's add the created app there. The variable to set is a tuple named ʻINSTALLED_APPS` near line 33 of settings.py.

tutorial/settings.py


INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'polls',  #← Add this
)

This time, I added my own polls app, but if you want to add a ready-made django application with pip etc., add the app name to INSTALLED_APPS as well. If you add it here, it will be loaded for migration, templates, test, etc.

4. Database update

Documents → https://docs.djangoproject.com/en/1.8/intro/tutorial01/#activating-models (Same as `3. Add application``)

After changing settings.py, execute the make migrations command. This command detects changes in the model of each application and automatically creates a migration file. By executing this command to create a migration file, and then executing the migrate command Reflect the model (= table) change in the DB.

$ ./manage.py makemigrations
Migrations for 'polls':
  0001_initial.py:
    - Create model Choice
    - Create model Question
    - Add field question to choice

If there is a change, it will be detected automatically and a migration file will be created. This time it is not a table addition, but if the default value is not set when adding the field You will be asked what the default value should be

$ ./manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: messages, staticfiles
  Apply all migrations: admin, auth, polls, contenttypes, sessions
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying polls.0001_initial... OK

By executing the migrate command, the settings will be reflected in the database. Which migrate command you executed is recorded in the django_migrations table.

-- In the original tutorial, after this, we will customize the model and execute it in the shell. I will omit it in this tutorial. Model customization will be explained in the next tutorial. https://docs.djangoproject.com/en/1.8/intro/tutorial01/#playing-with-the-api

-- To the next tutorial

Tutorial Summary

Recommended Posts

Python Django Tutorial (5)
Python Django Tutorial (8)
Python Django Tutorial (6)
Python Django Tutorial (7)
Python Django Tutorial (1)
Python Django tutorial tutorial
Python Django Tutorial (3)
Python Django Tutorial (4)
Python Django tutorial summary
Python tutorial
Python Django Tutorial Cheat Sheet
django tutorial memo
Start Django Tutorial 1
Django 1.11 started with Python3.6
[Docker] Tutorial (Python + php)
Django python web framework
Django Polymorphic Associations Tutorial
django oscar simple tutorial
Django Python shift table
Try Debian + Python 3.4 + django1.7 ...
[Personal notes] Python, Django
Python OpenCV tutorial memo
Django Girls Tutorial Note
Cloud Run tutorial (python)
Python Django CSS reflected
Do Django with CodeStar (Python3.6.8, Django2.2.9)
Get started with Django! ~ Tutorial ⑤ ~
Introduction to Python Django (2) Win
[Python tutorial] Control structure tool
Python
Do Django with CodeStar (Python3.8, Django2.1.15)
Python3 + Django ~ Mac ~ with Apache
Create ToDo List [Python Django]
Getting Started with Python Django (1)
Get started with Django! ~ Tutorial ④ ~
Django
Getting Started with Python Django (3)
Get started with Django! ~ Tutorial ⑥ ~
Install Python 3.7 and Django 3.0 (CentOS)
[Python] Decision Tree Personal Tutorial
GAE + python + Django addictive story
Getting Started with Python Django (6)
Getting Started with Python Django (5)
Until Python [Django] de Web service is released [Tutorial, Part 1]
EEG analysis in Python: Python MNE tutorial
Python practice_Virtual environment setup ~ Django installation
Create new application use python, django
python + django + scikit-learn + mecab (2) on heroku
Run python3 Django1.9 with mod_wsgi (deploy)
Django Girls Tutorial Summary First Half
Stumble when doing the django 1.7 tutorial
Deploy the Django tutorial to IIS ①
Install Python framework django using pip
Introduction to Python Django (2) Mac Edition
[Python Tutorial] An Easy Introduction to Python
Learning history for participating in team app development in Python ~ Django Tutorial 5 ~
Learning history for participating in team app development in Python ~ Django Tutorial 1, 2, 3 ~
Learning history for participating in team app development in Python ~ Django Tutorial 6 ~
Learning history for participating in team app development in Python ~ Django Tutorial 7 ~
Django Crispy Tutorial (Environment Building on Mac)
kafka python