初始化一个模块:博客
$ python3 manage.py startapp blog
app配置中添加 blog
打开/mydjango/mydjango/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog', #新添加
]
blog模块中,新加类型article、comment
打开 /mydjango/blog/models.py
,添加内容:
from django.db import models
# Create your models here.
class Article(models.Model):
# 无需写id,pymysql会自动生成自增长主键id
title = models.CharField(max_length=100, verbose_name='文章标题')
content = models.TextField(verbose_name='文章内容')
author = models.CharField(max_length=30, verbose_name='作者')
time = models.DateTimeField(auto_now=True, verbose_name='时间')
class Comment(models.Model):
articleid = models.IntegerField(verbose_name='文章id')
user = models.CharField(max_length=30, verbose_name='ls评论人')
content = models.CharField(max_length=100, verbose_name='评论内容')
time = models.DateTimeField(auto_now=True, verbose_name='时间')
更新变化到mysql
$ python3 manage.py migrate
.
报错...
No migrations to apply.
Your models have changes that are not yet reflected in a migration, and so won't be applied.
Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.
这里提示先执行manage.py makemigrations,然后执行manage.py migrate
$ python3 manage.py makemigrations
Migrations for 'blog':
blog/migrations/0001_initial.py
- Create model Article
- Create model Comment
$ python3 manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, blog, contenttypes, sessions
Running migrations:
Applying blog.0001_initial... OK
执行成功,查看数据库
表名是以 模块_类型
定义的
添加路由配置
打开/mydjango/mydjango/urls.py
,默认已存在下面配置,如果没有,则添加:
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
]
添加模块注册配置
打开/mydjango/blog/admin.py
,添加配置:
from django.contrib import admin
from .models import Article, Comment
# 文章模块
class ArticleAdmin(admin.ModelAdmin):
list_display = ['id', 'title', 'content', 'author', 'time']
# 搜索字段
search_fields = ('title', 'author',)
# 评论模块
class CommentAdmin(admin.ModelAdmin):
list_display = ['id', 'articleid', 'user', 'content', 'time']
#搜索字段
search_fields = ('user', 'content',)
# 注册模块url到后台
admin.site.register(Article, ArticleAdmin)
admin.site.register(Comment, CommentAdmin)
# 设置页面显示信息
admin.AdminSite.site_header = 'admin管理系统'
admin.AdminSite.site_title = 'django管理后台'
访问后台页面
浏览器访问 http://127.0.0.1:8000/admin ,多了BLOG的管理模块
添加数据
搜索数据,article可使用标题和作者搜索(因为上面的admin.py配置的)
# 文章模块
class ArticleAdmin(admin.ModelAdmin):
list_display = ['id', 'title', 'content', 'author', 'time']
# 搜索字段
search_fields = ('title', 'author',)
使用标题搜索
使用作者搜索
评论模块相似,不在概述。