From 164cc17ff9b806706da178304a4438eb31fe28a7 Mon Sep 17 00:00:00 2001 From: JasonHomeWorkstationUbuntu Date: Tue, 20 Oct 2020 14:22:46 +1100 Subject: [PATCH] Finished django app, part 2 --- .gitignore | 3 ++- first_django_app.md | 50 +++++++++++++++++++++++++++++++++--------- src/mysite/settings.py | 1 + src/polls/admin.py | 3 ++- src/polls/models.py | 25 +++++++++++++++++++-- 5 files changed, 68 insertions(+), 14 deletions(-) diff --git a/.gitignore b/.gitignore index ca5f1be..7a30346 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ .vscode **__pycache__** -**db.sqlite3** \ No newline at end of file +**db.sqlite3** +**/migrations** \ No newline at end of file diff --git a/first_django_app.md b/first_django_app.md index 3f7c9c0..7a78c64 100644 --- a/first_django_app.md +++ b/first_django_app.md @@ -5,7 +5,13 @@ Target: create a basic poll application, with 2 parts a **public site** and a ** * **public site**: let's pp view polls and vote * **admin site**: let's you(admin) add/change/delete poll -## Creating a project +## Part 1 + +1. Create web project +2. Create 1st app +3. Create 1st view +4. Add view & app into web url +### Creating a project In the source directory, create project by @@ -39,7 +45,7 @@ Explain file structure: * `mysite/asgi.py`: An entry-point for ASGI-compatible webservers * `mysite/wsgi.py`: Entry-point for WSGI-compatible webservers -## The development server +### The development server Start server steps: 1. cd into outer `mysite/` dir @@ -50,7 +56,7 @@ Outcome: * A development server is started. So no need to config a production server (e.g. Apache) * Note: don't use it as production environment. -## Creating the Polls app +### Creating the Polls app > Projects vs. apps > @@ -76,9 +82,9 @@ polls/ views.py ``` -## Write the first view +### Write the first view -### Step 1: Create a simple view of `polls` app +#### Step 1: Create a simple view of `polls` app modify `polls/views.py` as @@ -92,7 +98,7 @@ def index(request): * `def index(request):...` is the simplest view -### Step 2: In `polls` app, map the URL to this view +#### Step 2: In `polls` app, map the URL to this view After creating a view, map it to a URL so we can call it. Create `polls/urls.py`, and setup mapping `urlpatterns` @@ -106,7 +112,7 @@ urlpatterns = [ ] ``` -### Step 3: Point the root URLconf for polls +#### Step 3: Point the root URLconf for polls To point the root URLconf at `polls.urls` module: 1. In `mysite/urls.py` @@ -125,14 +131,14 @@ urlpatterns = [ ] ``` -#### django.urls.include() +##### django.urls.include() > django.urls.include(): A function that takes a full Python import path to another URLconf module that should be “included” in this place. * new imported `include()` function allows referencing other URLconfs. * `'polls.urls'` is the package that we are using, hence `mysite` can connect to `polls` app -#### path() +##### path() Here `path()` function is passed **route** and **view**; two additional option available **kwargs**, and **name** @@ -141,5 +147,29 @@ Here `path()` function is passed **route** and **view**; two additional option a * `path()` argument **kwargs**: passed in a dictionary to the target view * `path()` argument **name**: naming URL, so we can refer to it elsewhere. -## Database setup +## Part 2 +### Database setup + +1. Modify `mysite/settings.py` for database binding +2. `python manage.py migrate` create database for each app + +### Models Creation + +在 Django 里写一个数据库驱动的 Web 应用的第一步: **定义模型** - 也就是数据库结构设计和附加的其它元数据 Meta Data + +### Activate Models + +改变模型需要这三步: + +* 编辑 models.py 文件,改变模型 +* 运行 python manage.py makemigrations 为模型的改变生成迁移文件。 +* 运行 python manage.py migrate 来应用数据库迁移。 + +在这之前,确认polls已经在 INSTALLED_APPS的settings中。 + +详情如何使用 `manage.py` 可check [Django后台文档](https://docs.djangoproject.com/zh-hans/3.1/ref/django-admin/) + +### Test API + +进入 `python manage.py shell` 可以使用Django创建的各种API,如[数据库抽象API database API(建议细看)](https://docs.djangoproject.com/zh-hans/3.1/topics/db/queries/) \ No newline at end of file diff --git a/src/mysite/settings.py b/src/mysite/settings.py index 59351f4..2ead694 100644 --- a/src/mysite/settings.py +++ b/src/mysite/settings.py @@ -37,6 +37,7 @@ INSTALLED_APPS = [ 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', + 'polls.apps.PollsConfig', ] MIDDLEWARE = [ diff --git a/src/polls/admin.py b/src/polls/admin.py index 8c38f3f..38576f7 100644 --- a/src/polls/admin.py +++ b/src/polls/admin.py @@ -1,3 +1,4 @@ from django.contrib import admin -# Register your models here. +from .models import Question +admin.site.register(Question) \ No newline at end of file diff --git a/src/polls/models.py b/src/polls/models.py index 71a8362..4e428ec 100644 --- a/src/polls/models.py +++ b/src/polls/models.py @@ -1,3 +1,24 @@ -from django.db import models +import datetime -# Create your models here. +from django.db import models +from django.utils import timezone as djtz + +class Question(models.Model): + # question_text & pub_date are instances of field + question_text = models.CharField(max_length=200) + pub_date = models.DateTimeField('date published') + + def was_published_recently(self): + return self.pub_date >= djtz.now() - datetime.timedelta(days=1) + + def __str__(self) -> str: + return self.question_text + +class Choice(models.Model): + # ForeinKey to define a relationship, here tells Choice object is mapped to a Question + question = models.ForeignKey(Question, on_delete=models.CASCADE) + choice_text = models.CharField(max_length=200) + votes = models.IntegerField(default=0) + + def __str__(self) -> str: + return self.choice_text \ No newline at end of file