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.
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 WindowsScripts \ 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
Let's open the generated project in PyCharm.
3.Location: Click the folder icon on the right and select the mybook folder you just generated.
For Windows, it is C: \ Users \ hoge \ PycharmProjects \ mybook.
For Windows, it is C: \ Users \ hoge \ Documents \ env1 \ python.exe.
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 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.
The end of the development server is control + c
.
Just press the bug mark at the top right of the screen. Alternatively, select Run> Debug ..> mybook from the menu.
It is OK if the following display appears below. When you want to stop, press the red square button.
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.
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/
:
:
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
.
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:
- Fix models.py
- $ python manage.py makemigrations app name… pick up changes in models.py and create a migrate file
- $ python manage.py migrate… Reflect the migrate file in the database
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.
Start the development server with python manage.py runserver
.
Access http://127.0.0.1:8000/admin/
with a browser.
Log in as the superuser ʻadmin / hogefuga initialized with the first
$ python manage.py createsuperuser`.
You can only see groups and users yet.
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.
Please try adding, modifying, and deleting data.
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)
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