Getting Started with Python Django (3)

Get started with Django

document

It's a good idea to read "If you start from nothing: Overview" and "Tutorial here: Part 1-7", but you can try this course first.

Try making it with Django

Creating a project

Let's create an app that manages simple books.

First, create a project called mybook. To do this, use the command django-admin startproject mybook.

When you try to create a project with PyCharm, it seems that a folder called PycharmProjects will be created, so I will create it under that

Make sure you are in the virtual environment of (env1). If you already have it, you don't need the following Mac workon env1 and Windows Scripts \ activate.

For Mac,

$ workon env1

(env1) $ cd ~/PycharmProjects/
(env1) $ django-admin startproject mybook

For Windows,

C:¥Users¥hoge>cd Documents¥env1
C:¥Users¥hoge¥Documents¥env1> Scripts¥activate

(env1) C:¥Users¥hoge¥Documents¥env1> cd C:¥Users¥hoge¥PycharmProjects
(env1) C:¥Users¥hoge¥PycharmProjects> django-admin startproject mybook

From here, the explanation returns to the Mac assumption. For Windows, please read as each environment.

Files created in ~ / PycharmProjects /

mybook/
    manage.py
    mybook/
        __init__.py
        asgi.py
        settings.py
        urls.py
        wsgi.py

Go into the mybook directory.

$ cd mybook

Open a project in PyCharm

Let's open the generated project in PyCharm.

  1. Select Create New Project

Welcome_to_PyCharm.jpg

  1. Select Django on the left.

New_Project_01.png

3.Location: Click the folder icon on the right and select the mybook folder you just generated.

New_Project_02.png

For Windows, it is C: \ Users \ hoge \ PycharmProjects \ mybook.

  1. Click the Project Interpreter: triangle icon to expand it and select the Interpreter "..." for the Existing Interpreter.

New_Project_11.png

  1. Select "..." in Virtualenv Environment> Interpreter.

New_Project_12.png

  1. Select Python3 for the env1 virtual environment as the Python interpreter

New_Project_13.png

For Windows, it is C: \ Users \ hoge \ Documents \ env1 \ python.exe.

  1. Click OK to close.

New_Project_14.png

  1. Press the Create button (reconfirm that Django is on the left)

New_Project_15.png

  1. I already have it, but I'm asked if it's okay, so answer Yes

New_Project_06.png

  1. If you can do it like this, you are successful

New_Project_07.png

Database setup

The database settings are in mybook / settings.py, but by default it is already set to use SQlite3.

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

    :

# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

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

While looking at mybook / settings.py, set the language and timezone to Japan.

# Means a commented out line. To comment out For Mac, position it on a line (if there are multiple lines, select the line) and command + /. For Windows, Ctrl + /. Hmm convenient.

# LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'ja'

# TIME_ZONE = 'UTC'
TIME_ZONE = 'Asia/Tokyo'

When you enter the command to migrate the database, a file called db.sqlite3 will be created in the directory directly under the project.


$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... 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 auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying sessions.0001_initial... OK

Create a superuser with the following command.

$ python manage.py createsuperuser
username(leave blank to use 'hoge'): admin
mail address: [email protected]
Password: hogefuga
Password (again): hogefuga
Superuser created successfully.

On the way, answer the following questions.

Start the development server

Start the development server with the command python manage.py runserver to see if the project works.

$ python manage.py runserver

Performing system checks...

System check identified no issues (0 silenced).
January 08, 2020 - 16:20:02
Django version 3.0.2, using settings 'mybook.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Try accessing http://127.0.0.1:8000/ with your browser.

dango01.png

The end of the development server is control + c.

Debug with PyCharm

Just press the bug mark at the top right of the screen. Alternatively, select Run> Debug ..> mybook from the menu.

debug.png

It is OK if the following display appears below. When you want to stop, press the red square button.

stop.png

Like a typical IDE, you can set breakpoints and check variables by clicking around the right side of the line number in your code.

Once stopped, the Debug window is in the way, so press the collapse button.

fold.png

Creating an application

Let's create an application called cms under the project.

cms is like a Content management system, like master maintenance. An application is a unit of functionality that makes up a project, and in some cases can be reused.

Create it with the following command.

$ python manage.py startapp cms

The following files have been created under the mybook project directory.

mybook/
    cms/
        __init__.py
        admin.py
        apps.py
        migrations/
            __init__.py
        models.py
        tests.py
        views.py
    manage.py
    mybook/
       :
       :

Creating a model

Define the data model you want to define in the database in cms / models.py.

Before class, if you do not open two lines, a wavy line will appear and you will be warned. It is a code style check mechanism called pep8. Similarly, if the end of the code does not end with only a line break, wavy lines will appear again and you will get angry, so be careful.

from django.db import models


class Book(models.Model):
    """Books"""
    name = models.CharField('Book title', max_length=255)
    publisher = models.CharField('the publisher', max_length=255, blank=True)
    page = models.IntegerField('number of pages', blank=True, default=0)

    def __str__(self):
        return self.name


class Impression(models.Model):
    """Impressions"""
    book = models.ForeignKey(Book, verbose_name='Books', related_name='impressions', on_delete=models.CASCADE)
    comment = models.TextField('comment', blank=True)

    def __str__(self):
        return self.comment
        

The impression is a child's model associated with the book.

Enable the model

You need to tell your project that you have installed the cms application. If you open cms / apps.py, you will see a class called CmsConfig defined. Add this to the end of ʻINSTALLED_APPS in mybook / settings.pywith the string'cms.apps.CmsConfig',`.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'cms.apps.CmsConfig',   #cms application
]

The following command will pick up the changes in models.py and create a migrate file.

$ python manage.py makemigrations cms
Migrations for 'cms':
  cms/migrations/0001_initial.py
    - Create model Book
    - Create model Impression

You can check what kind of SQL this migrated file will be with the following command.

$ python manage.py sqlmigrate cms 0001
BEGIN;
--
-- Create model Book
--
CREATE TABLE "cms_book" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(255) NOT NULL, "publisher" varchar(255) NOT NULL, "page" integer NOT NULL);
--
-- Create model Impression
--
CREATE TABLE "cms_impression" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "comment" text NOT NULL, "book_id" integer NOT NULL REFERENCES "cms_book" ("id") DEFERRABLE INITIALLY DEFERRED);
CREATE INDEX "cms_impression_book_id_b2966102" ON "cms_impression" ("book_id");
COMMIT;

Use the following command to reflect the migrate file that has not been reflected in the database to the database.

$ python manage.py migrate cms

Operations to perform:
  Apply all migrations: cms
Running migrations:
  Applying cms.0001_initial... OK

Starting with Django 1.7, the database migration tool is included by default, so if you want to add / modify items in a new table or an existing table, for example, your daily routine work would be:

  1. Fix models.py
  2. $ python manage.py makemigrations app name… pick up changes in models.py and create a migrate file
  3. $ python manage.py migrate… Reflect the migrate file in the database

Enable management site

Here's what Django is all about.

Django doesn't have application stationery like scaffold, which means it doesn't automatically generate CRUD (Create, Read, Update, Delete). Instead, there is a management site, from which all master maintenance data can be input.

Let's display the management site.

  1. Start the development server with python manage.py runserver.

  2. Access http://127.0.0.1:8000/admin/ with a browser.

  3. Log in as the superuser ʻadmin / hogefuga initialized with the first $ python manage.py createsuperuser`.

django02.jpg

You can only see groups and users yet.

django03.jpg

Allow cms models to be edited on admin

Add the model you want to display on the admin site to cms / admin.py.

from django.contrib import admin
from cms.models import Book, Impression

admin.site.register(Book)
admin.site.register(Impression)

Let's take a look at http://127.0.0.1:8000/admin/ again.

django04.jpg

Please try adding, modifying, and deleting data.

django05.jpg

django06.jpg

Customize the management site list page

When looking at the list of management sites, in models.py

def __str__(self):

What you set in is visible as the record name.

Let's modify cms / admin.py so that we can see the whole record item a little more.

Before class, if you do not open two lines, a wavy line will appear and you will be warned.

from django.contrib import admin

from cms.models import Book, Impression

# admin.site.register(Book)
# admin.site.register(Impression)


class BookAdmin(admin.ModelAdmin):
    list_display = ('id', 'name', 'publisher', 'page',)  #Items you want to list
    list_display_links = ('id', 'name',)  #Items that can be clicked with the correction link


admin.site.register(Book, BookAdmin)


class ImpressionAdmin(admin.ModelAdmin):
    list_display = ('id', 'comment',)
    list_display_links = ('id', 'comment',)
    raw_id_fields = ('book',)   #Do not pull down the foreign key (prevent timeout when the number of data increases)


admin.site.register(Impression, ImpressionAdmin)

django07.jpg

How about that.

You can easily list, register, modify, and delete the tables you have added to your model. You don't need an explanation of how to make CRUD, right?

That doesn't explain Django, so let's explain how to create CRUD by yourself.

Continue to Introduction to Python Django (4)

Recommended Posts

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)
Getting Started with Python
Getting Started with Django 1
Getting Started with Python
Getting Started with Django 2
Getting Started with Python Functions
Getting Started with Django with PyCharm
Python3 | Getting Started with numpy
Getting Started with Python responder v2
Getting Started with Python Web Applications
Getting Started with Python for PHPer-Classes
Getting Started with Python Basics of Python
Getting Started with Python Genetic Algorithms
Getting started with Python 3.8 on Windows
Getting Started with Python for PHPer-Functions
Getting Started with python3 # 1 Learn Basic Knowledge
Getting started with Android!
Getting Started with Golang 2
Getting Started with Python Web Scraping Practice
Getting started with apache2
Getting Started with Golang 1
Getting Started with Optimization
Getting Started with Python for PHPer-Super Basics
Getting Started with Python Web Scraping Practice
Getting started with Dynamo from Python boto
Getting Started with Golang 3
Getting Started with Numpy
Getting started with Spark
Getting Started with Pydantic
Getting Started with Golang 4
Getting Started with Jython
Getting Started with Heroku-Viewing Hello World in Python Django with Raspberry PI 3
Getting started with Python with 100 knocks on language processing
[Translation] Getting Started with Rust for Python Programmers
Django Getting Started Part 2 with eclipse Plugin (PyDev)
Getting started with AWS IoT easily in Python
Django Getting Started Part 3 about Python3 & MySQL Connector
Materials to read when getting started with Python
Settings for getting started with MongoDB in python
Do Django with CodeStar (Python3.6.8, Django2.2.9)
Getting Started with Tkinter 2: Buttons
Get started with Django! ~ Tutorial ⑤ ~
Getting Started with Go Assembly
Getting Started with PKI with Golang ―― 4
Django Getting Started: 2_ Project Creation
Django Getting Started: 1_Environment Building
Python3 + Django ~ Mac ~ with Apache
Django Getting Started: 3_Apache integration
Get started with Django! ~ Tutorial ④ ~
Get started with Django! ~ Tutorial ⑥ ~
Get started with Python! ~ ② Grammar ~
Getting Started with python3 # 2 Learn about types and variables
Getting Started with Google App Engine for Python & PHP
started python
Link to get started with python
Getting Started with Git (1) History Storage
Getting started with Sphinx. Generate docstring with Sphinx