安装django模块
pip install django==xxx
版本确认
python -m django --version
启动项目
python manage.py runserver [0:8000]|[8000]
创建项目
django-admin startproject mysite
创建应用
python manage.py startapp blog
创建视图
blog/views.py创建http响应调用html视图
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
# --------------------------分割新-------------------------- #
from django.shortcuts import render
# 调用 templates/blog/index.html html模板
def index(request):
return render(request, 'blog/index.html')
blog/urls.py (首次需新建)
from django.urls import path
from . import views
# https://docs.djangoproject.com/en/3.0/ref/urls/#django.urls.path
urlpatterns = [
path('', views.index, name='index'),
]
mysite/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('blog/', include('blog.urls')),
path('admin/', admin.site.urls),
]
配置数据库
mysite/settings.py
# 默认使用sqlite模块
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# 修改为mysql模块, 需按照mysqlclient插件
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': os.path.join(BASE_DIR, 'conf', 'db.conf'),
},
}
}
conf/db.conf
[client]
database = db_django
user = root
password = toor
host = 127.0.0.1
port = 3306
default-character-set = utf8
配置Model
mysite/settings.py
INSTALLED_APPS = [
'blog.apps.BlogConfig',
# ...
]
待创建sql表schema
# TableSchema
# `id` int unsigned NOT NULL AUTO_INCREMENT COMMENT '主键编号',
# `title` text NOT NULL COMMENT '标题',
# `alias` varchar(256) NOT NULL DEFAULT '' COMMENT '别名',
# `content` mediumtext NOT NULL COMMENT '正文',
# `tag` varchar(256) DEFAULT '' COMMENT '标签',
# `author` varchar(64) NOT NULL DEFAULT '' COMMENT '作者',
# `istop` tinyint DEFAULT '9' COMMENT '是否置顶 1置顶 9正常',
# `iscomment` tinyint DEFAULT '9' COMMENT '是否评论 1评论 9不评论',
# `sort` tinyint unsigned NOT NULL DEFAULT '255' COMMENT '文章排序 默认255',
# `status` tinyint NOT NULL DEFAULT '1' COMMENT '文章状态 1正常 3草稿 9删除',
# `created_at` int DEFAULT '0',
# `updated_at` int DEFAULT '0',
# `deleted_at` int DEFAULT '0',
blog/models.py
from django.db import models
# Create your models here.
class Blogs(models.Model):
title = models.TextField('标题', null=False)
alias = models.CharField('别名', max_length=256, default='')
content = models.TextField('正文', null=False)
tag = models.CharField('标签', max_length=256, default='')
author = models.CharField('作者', max_length=64, default='')
istop = models.SmallIntegerField('是否置顶 1置顶 9正常', default=9)
iscomment = models.SmallIntegerField('是否评论 1评论 9不评论', default=9)
sort = models.PositiveSmallIntegerField('文章排序 默认255', default=255)
status = models.SmallIntegerField('文章状态 1正常 3草稿 9删除', default=1)
created_at = models.IntegerField(default=0)
updated_at = models.IntegerField(default=0)
deleted_at = models.IntegerField(default=0)
***_initial.py
python manage.py makemigrations blog
# 执行结果
migrations.CreateModel(
name='blog',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.TextField(verbose_name='标题')),
('alias', models.CharField(default='', max_length=256, verbose_name='别名')),
('content', models.TextField(verbose_name='正文')),
('author', models.CharField(default='', max_length=64, verbose_name='作者')),
('istop', models.SmallIntegerField(default=9, verbose_name='是否置顶 1置顶 9正常')),
('iscomment', models.SmallIntegerField(default=9, verbose_name='是否评论 1评论 9不评论')),
('sort', models.PositiveSmallIntegerField(default=255, verbose_name='文章排序 默认255')),
('status', models.SmallIntegerField(default=1, verbose_name='文章状态 1正常 3草稿 9删除')),
('tag', models.CharField(default='', max_length=256, verbose_name='标签')),
('created_at', models.IntegerField(default=0)),
('updated_at', models.IntegerField(default=0)),
('deleted_at', models.IntegerField(default=0)),
],
),
0001_initial.py
python manage.py sqlmigrate blog 0001
# 执行结果, 好像不符合预期, 注释、默认值都未生效, 先凑合用
--
-- Create model Blogs
--
CREATE TABLE `blog_blogs` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`title` longtext NOT NULL,
`alias` varchar(256) NOT NULL,
`content` longtext NOT NULL,
`author` varchar(64) NOT NULL,
`istop` smallint NOT NULL,
`iscomment` smallint NOT NULL,
`sort` smallint UNSIGNED NOT NULL CHECK (`sort` >= 0),
`status` smallint NOT NULL,
`tag` varchar(256) NOT NULL,
`created_at` integer NOT NULL,
`updated_at` integer NOT NULL,
`deleted_at` integer NOT NULL
);
appNamemodelName
python manage.py migrate
若执行, 则生成一堆表
# mysql> show tables;
# +----------------------------+
# | Tables_in_db_django |
# +----------------------------+
# | auth_group |
# | auth_group_permissions |
# | auth_permission |
# | auth_user |
# | auth_user_groups |
# | auth_user_user_permissions |
# | blog_blogs |
# | django_admin_log |
# | django_content_type |
# | django_migrations |
# | django_session |
# +----------------------------+
操作Model
blog/urls.py新增查询
urlpatterns = [
# ...
path('save/', views.save, name='save'),
path('detail/<int:uid>/', views.detail, name='detail'),
]
blog/views.py
import time
# ...
from .models import Blogs
# ...
def save(request):
blog = Blogs(
title='博客测试',
alias='测试',
content='博客正文',
tag='测试',
author='最爱啥都想',
created_at=int(time.time())
)
blog.save()
return HttpResponse("新增记录完成, pk={}".format(blog.id))
http://127.0.0.1:8000/blog/save/
blog/views.py
import time
# ...
from .models import Blogs
# ...
def detail(request, uid):
blog = Blogs.objects.get(pk=uid)
return HttpResponse(json.dumps({
'id': blog.id,
'title': blog.title,
'alias': blog.alias,
'content': blog.content,
'author': blog.author,
'istop': blog.istop,
'iscomment': blog.iscomment,
'sort': blog.sort,
'tag': blog.tag,
'created_at': blog.created_at,
'updated_at': blog._format_updated(),
'deleted_at': blog.deleted_at,
}, ensure_ascii=False))
# --------------------------分割新-------------------------- #
import time
# ...
from .models import Blogs
# ...
# 调用 templates/blog/detail.html 视图
def detail(request, uid):
blog = Blogs.objects.get(pk=uid)
return render(request, 'blog/detail.html', {'detail': {
'id': blog.id,
'title': blog.title,
'alias': blog.alias,
'content': blog.content,
'author': blog.author,
'istop': blog.istop,
'iscomment': blog.iscomment,
'sort': blog.sort,
'tag': blog.tag,
'created_at': blog.created_at,
'updated_at': blog._format_updated(),
'deleted_at': blog.deleted_at,
}})
# --- #
<div class="container">
<table class="table">
<caption>Blog 编号.{{ detail.id }}</caption>
<thead>
<tr>
<th>字段</th>
<th>数据</th>
</tr>
</thead>
<tbody>
{% for key, value in detail.items %}
<tr>
<th>{{ key }}</th>
<th>{{ value }}</th>
</tr>
{% endfor %}
</tbody>
</table>
</div>
数据库中数据
mysql> select * from blog_blogs where id = 1\G
# *************************** 1. row ***************************
# id: 1
# title: 博客测试
# alias: 测试
# content: 博客正文
# author: 最爱啥都想
# istop: 9
# iscomment: 9
# sort: 255
# status: 1
# tag: 测试
# created_at: 1594047925
# updated_at: 0
# deleted_at: 0
# 1 row in set (0.01 sec)
http://127.0.0.1:8000/blog/detail/1/
-
返回http响应
image.png -
返回detail视图
image.png
至此, Django入门教程完结.