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-
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>
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)
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>
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>]>
>>>
(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>
(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/.
When you log in, you will see a screen like this.
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)
The Polls app Question has been added.
At the destination where I clicked Question and transitioned, there was "What'S This?" It seems that you can create or edit new questions.
Today is up to here. Thank you very much.
Recommended Posts