上一篇:老菜鸟学习 Django (一)
python manage.py startapp polls
这将创建一个目录 polls,其布局如下所示:
polls/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
在 views.py 编辑你的第一个视图
from django.shortcuts import render
# Create your views here.
from django import HttpResponse
def index(request):
return HttpResponse("Hello,world.You're at the polls index。")
polls 新建 urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
mysite 修改 urls.py
from django.urls import include, path
from django.contrib import admin
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
运行
python manage.py runserver 8001
打开链接http://localhost:8001/polls/,查看页面显示,看到文本 Hello,world.You're at the polls index。
mysite 配置 settings.py
# Application definition
INSTALLED_APPS = [
# 管理网站
'django.contrib.admin',
# 一个认证系统
'django.contrib.auth',
# 内容类型的框架
'django.contrib.contenttypes',
# 会话框架
'django.contrib.sessions',
# 消息传递框架
'django.contrib.messages',
# 一个管理静态文件的框架
'django.contrib.staticfiles',
]
# 默认使用SQLite数据库
DATABASES = {
'default': {
# ENGINE包括:'django.db.backends.sqlite3','django.db.backends.postgresql',
# 'django.db.backends.mysql','django.db.backends.oracle'
'ENGINE': 'django.db.backends.sqlite3',
# NAME:数据库的名称
# 如果你不使用SQLite作为数据库,额外的设置,例如 USER,PASSWORD和HOST必须加入
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# 设置时区,可以选择'Asia/Shanghai'或者'Asia/Chengdu'
TIME_ZONE = 'Asia/Shanghai'
创建表格
python manage.py migrate
polls 编辑 models.py
from django.db import models
# Create your models here.
class Question(models.Model):
# 创建Question类,类里有一个question_text,和一个pub_date
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
# 创建Choice类,类里有一个choice_text,和一个votes
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
mysite 修改 settings.py
# Application definition
INSTALLED_APPS = [
# 引用polls的配置类PollsConfig,它包含在polls/apps中
'polls.apps.PollsConfig',
# 管理网站
'django.contrib.admin',
# 一个认证系统
'django.contrib.auth',
# 内容类型的框架
'django.contrib.contenttypes',
# 会话框架
'django.contrib.sessions',
# 消息传递框架
'django.contrib.messages',
# 一个管理静态文件的框架
'django.contrib.staticfiles',
]
运行 makemigrations,您告诉 Django 您已经对模型进行了一些更改,并更改存储为迁移
python manage.py makemigrations polls
结果如下
Migrations for 'polls':
polls/migrations/0001_initial.py:
- Create model Choice
- Create model Question
- Add field question to choice
运行迁移并自动管理你的数据库模式
python manage.py sqlmigrate polls 0001
结果如下
BEGIN;
--
-- Create model Choice
--
CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);
--
-- 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);
--
-- Add field question to choice
--
ALTER TABLE "polls_choice" RENAME TO "polls_choice__old";
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);
INSERT INTO "polls_choice" ("id", "choice_text", "votes", "question_id") SELECT "id", "choice_text", "votes", NULL FROM "polls_choice__old";
DROP TABLE "polls_choice__old";
CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id");
COMMIT;
运行下列命令,检查是否有问题
python manage.py check
再次运行 migrate,创建模型表
python manage.py migrate
结果如下
Operations to perform:
Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
Applying polls.0001_initial... OK
polls 修改 model.py
from django.db import models
import datetime
from django.utils import timezone
# Create your models here.
class Question(models.Model):
# 创建Question类,类里有一个question_text,和一个pub_date
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
# 增加一个__str__方法,用处:一、方便处理交互提示;二:在Django的自动生成的admin中使用对象的表示
return self.question_text
def was_published_recently(self):
# 增加自定义方法
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
# 创建Choice类,类里有一个choice_text,和一个votes
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
创建管理员用户
python manage.py createsuperuser
输入用户名并回车
Username: admin
输入电子邮件地址并回车
Email address: admin@example.com
输入密码并回车,再次输入密码并回车,提示成功
Password: 123456abAB
Password (again): 123456abAB
Superuser created successfully.
运行命令,启动服务器
python manage.py runserver 8001
打开链接http://localhost:8001/admin/,进入登陆页,输入账号密码登陆
如果提示端口被占用
lsof -i tcp:port (port 替换成端口号,比如 8001)
找到占用端口的 pid
kill pid(pid 替换成占用端口的 pid 号)
polls 编辑 admin.py,增加 Question,显示在 admin 页面上
from django.contrib import admin
from .models import Question
# Register your models here.
admin.site.register(Question)