[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 2-

Introduction

Nice to meet you, everyone. I'm going to publish a memorandum of the process of creating a voting (poll) application using Django. Since I am a beginner of Qiita, please understand that some parts may be difficult to read.

series

-[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-No. 0- -[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 1-

Start work

Database settings

The Django tutorial uses SQLite (a lightweight RDBMS). (It is stated that it is better to use the expandable OSS DB in the production environment.)

When using a DB other than SQLite, change DATABASE> default> ENGINE. You also need to make additional settings such as USER, PASSWORD, and HOST.

condig/settings.py



DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

Migrate the DB. The literal translation of "migrate" means "move / migrate", and here it should be understood that it is a function to create and commit the DB definition used in the application.


(poll-HcNSSqhc) C:\django\poll>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 auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK

(poll-HcNSSqhc) C:\django\poll>

Creating a model

Create a Model for MVC. Model is a function that processes data through DB. In polls / models.py, specify DB tables and columns.

polls/modeles.py


from django.db import models

# Create your models here.

#Table: polls_Question
#Column: question_text VARCHAR(200), pub_date DATETIME


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

#Table: polls_Choice
#Column: question FOREIGN(CASCADE) KEY, choice_text VARCHAR(200), votes INTEGER
# CASCADE=Foreign key constraint Follows a change in reference destination Deleted as soon as there is no reference destination


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

Enable the model

Register that you have installed the polls application (see PollsConfig class) in your config project.

polls/apps.py



from django.apps import AppConfig


class PollsConfig(AppConfig):
    name = 'polls'

Write polls / apps.py> PollsConfig in config / setting.py with dots.

config/setting.py



INSTALLED_APPS = [
    'polls.apps.PollsConfig'
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

DB migration. I will change the model, but it is just a temporary file, and it will not be migrated (committed) to the DB.


(poll-HcNSSqhc) C:\django\poll>python manage.py makemigrations polls
Migrations for 'polls':
  polls\migrations\0001_initial.py
    - Create model Question
    - Create model Choice

(poll-HcNSSqhc) C:\django\poll>

You can check the actual operation of DB migration as follows. SQL such as CREATE TABLE, CREATE INDEX, COMMIT has been issued.


(poll-HcNSSqhc) C:\django\poll>python manage.py sqlmigrate polls 0001
BEGIN;
--
-- Create model Question
--
CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);
--
-- Create model Choice
--
CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "polls_question" ("id") DEFERRABLE INITIALLY DEFERRED);
CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id");
COMMIT;

(poll-HcNSSqhc) C:\django\poll>

DB migrate. That is, commit to the DB.


(poll-HcNSSqhc) C:\django\poll>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
  Applying polls.0001_initial... OK

(poll-HcNSSqhc) C:\django\poll>

Play with the API

Let's start Python in interactive mode.

(poll-HcNSSqhc) C:\django\poll>python manage.py shell
Python 3.8.6 (tags/v3.8.6:db45529, Sep 23 2020, 15:37:30) [MSC v.1927 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> 

We will operate the DB with shell. Load the Choice and Question classes from the polls / models.py file. There are no objects (questions) yet.


>>> from polls.models import Choice,Question
>>> Question.objects.all()
<QuerySet []>
>>> 

Create an object (question).


>>> from django.utils import timezone
>>> 
>>> q=Question(question_text="What's new?",pub_date=timezone.now()) 
>>> q.save()
>>> 
>>> q.id
1
>>>
>>> q.question_text
"What's new?"
>>>
>>> q.pub_date
datetime.datetime(2020, 10, 6, 8, 27, 6, 527001, tzinfo=<UTC>)
>>>

Save and check the object (question). Since the return value is 1, it seems to exist.


>>> q.save()
>>> Question.objects.all()
<QuerySet [<Question: Question object (1)>]>
>>>

However, with a return value of 1, the contents of the object are unknown. Let's display the contents. Edit polls / models.py.

polls/modeles.py



import datetime
from django.db import models
from django.utils import timezone

# Create your models here.

#Table: polls_Question
#Column: question_text VARCHAR(200), pub_date DATETIME


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

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

#Table: polls_Choice
#Column: question FOREIGN(CASCADE) KEY, choice_text VARCHAR(200), votes INTEGER(Initial value 0)
# CASCADE=Foreign key constraint Follows a change in reference destination Deleted as soon as there is no reference destination


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

    def __str__(self):
        return self.choice_text

Check the object (question) again


>>> from polls.models import Choice, Question
>>> 
>>> Question.objects.all()
<QuerySet [<Question: What's>]>
>>> 

Let's see how to retrieve various data.


>>> Question.objects.filter(id=1)
<QuerySet [<Question: What's>]>
>>>

>>> Question.objects.get(pk=1)
<Question: What's>
>>>

Determine if the election day (pub_date) is within one day.


>>> q = Question.objects.get(pk=1)                              
>>>     
>>> q.was_published_recently()
True
>>>

Create the data of the Choice table that the Question externally references. That is, create a choice for the question. At this point, the question-choice relationship is one-to-many.


#Declare to create options for a particular question
>>> q.choice_set.all()
<QuerySet []>
>>> 
#Create 3 choices Question object → Accessing Choice object
>>> q.choice_set.create(choice_text='Not much', votes=0)
<Choice: Not much>
>>> 
>>> q.choice_set.create(choice_text='The sky', votes=0)
<Choice: The sky>
>>> 
>>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)
>>> 
#Choice object → Question object is also accessible
>>> c.question
<Question: What''s this?>
>>>
#Check all options
>>> q.choice_set.all()
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
>>>
>>> q.choice_set.count()
3
>>> 
>>> Choice.objects.filter(question__pub_date__year=current_year)
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
>>>
#Delete one Choice
>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()
(1, {'polls.Choice': 1})
>>> 
>>> q.choice_set.all()
<QuerySet [<Choice: Not much>, <Choice: The sky>]>
>>> 

Introducing Django Admin

Create an admin user


(poll-HcNSSqhc) C:\django\poll>python manage.py createsuperuser
Username (leave blank to use '***'): admin
Email address: [email protected]
Password:
Password (again):
The password is too similar to the username.
This password is too short. It must contain at least 8 characters.
This password is too common.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

(poll-HcNSSqhc) C:\django\poll>

Start development server


(poll-HcNSSqhc) C:\django\poll>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
October 06, 2020 - 21:09:30
Django version 3.1.2, using settings 'config.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

Go to http://127.0.0.1:8000/admin/. image.png

Enter the admin site

When you log in, you will see a screen like this. image.png

Allow Poll apps to be edited on admin

Add to polls / admin.py.

polls/admin.py



from django.contrib import admin

# Register your models here.
from .mdoeles import Question

admin.site.register(Question)

Explore the features of admin

The Polls app Question has been added.

image.png

At the destination where I clicked Question and transitioned, there was "What'S This?" It seems that you can create or edit new questions.

image.png

Today is up to here. Thank you very much.

Recommended Posts

[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 7-
[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 2-
[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 0-
[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 5-
[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 6-
[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 4-
[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 3-
Django python web framework
Deploy a Python 3.6 / Django / Postgres web app on Azure
(Python) Try to develop a web application using Django
CTF beginner tried to build a problem server (web) [Problem]
Web scraping beginner with python
[Django3] Display a web page in Django3 + WSL + Python virtual environment
A liberal arts engineer tried knocking 100 language processes in Python 02
A python beginner tried to intern at an IT company
A liberal arts engineer tried knocking 100 language processes in Python 01
A liberal arts engineer tried knocking 100 language processes in Python 00
If you know Python, you can make a web application with Django
[Python / Django] Create a web API that responds in JSON format
I tried web scraping with python.
Build a web application with Django
Python beginner tried 100 language processing knock 2015 (05 ~ 09)
web coder tried excel in Python
When a Python beginner tried using Bottle, it worked unexpectedly easily.
Python beginner tried 100 language processing knock 2015 (00 ~ 04)
A beginner of machine learning tried to predict Arima Kinen with python
An introduction to self-made Python web applications for a sluggish third-year web engineer
A note where a Python beginner got stuck
[Beginner] Python web scraping using Google Colaboratory
I have a question! (Python, django) Easy
Daemonize a Python web app with Supervisor
I tried a functional language with Python
[Python] A quick web application with Bottle!
I tried to make a Web API
Use Django from a local Python script
Run a Python web application with Docker
Let's make a web framework with Python! (1)
I tried benchmarking a web application framework
Let's make a web framework with Python! (2)
I made a WEB application with Django
A python beginner tried to intern at an IT company [Day 2 chatbot survey]
A python beginner tried to intern at an IT company [Day 1 development process]
[ES Lab] I tried to develop a WEB application with Python and Flask ②
I searched for the skills needed to become a web engineer in Python
2-2. Input for becoming a WEB engineer (Linux basics)
How to open a web browser from python
I tried web scraping using python and selenium
Python web framework Django vs Pyramid vs Flask December 2015
I tried playing a typing game in Python
Start a simple Python web server with Docker
[Python] Build a Django development environment with Docker
[Memo] I tried a pivot table in Python
[Python] Draw a Mickey Mouse with Turtle [Beginner]
Create a web map using Python and GDAL
Steps to develop a web application in Python
[Python] Web development preparation (building a virtual environment)
I tried reading a CSV file using Python
Programming beginner Python3 engineer certification basic exam record
Launch a web server with Python and Flask
Machine learning memo of a fledgling engineer Part 2
Run a Python file from html using Django