现在打开sxbweb
文件夹下的应用模型文件models.py
编辑基础的应用模型:
from django.db import models
from django.contrib.auth.models import User
class ItemType(models.Model):
type_name = models.CharField(max_length=30)
class Item(models.Model):
title = models.CharField(max_length=30)
blog_type = models.ForeignKey(ItemType, on_delete=models.DO_NOTHING)
content = models.TextField()
author = models.ForeignKey(User, on_delete=models.DO_NOTHING)
created_time = models.DateTimeField(auto_now_add=True)
last_update_time = models.DateTimeField(auto_now=True)
代码变更:
这里使用了VSCode进行代码编辑,之后的命令行代码均已VSCode中PowerShell的样式呈现。
(sxb_env) PS C:\Users\xiaoxi\Desktop\sxb_env\sxb> python .\manage.py migrate
(sxb_env) PS C:\Users\xiaoxi\Desktop\sxb_env\sxb> python .\manage.py createsuperuser
Username (leave blank to use 'xiaoxi'): xiaoxi
Email address: xiao-xi@example.com
Password:
Password (again):
This password is too short. It must contain at least 8 characters.
This password is entirely numeric.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.
打开项目设置文件,在其中注册应用sxbweb
,其位于:C:\Users\xiaoxi\Desktop\sxb_env\sxb\sxb\settings.py
:
...
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'sxbweb', # 注册应用
]
...
(sxb_env) PS C:\Users\xiaoxi\Desktop\sxb_env\sxb> python .\manage.py makemigrations
Migrations for 'sxbweb':
sxbweb\migrations\0001_initial.py
- Create model ItemType
- Create model Item
接下来将迁移文件同步至数据库:
(sxb_env) PS C:\Users\xiaoxi\Desktop\sxb_env\sxb> python .\manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, sxbweb
Running migrations:
Applying sxbweb.0001_initial... OK
自定义应用的后台显示表单,打开C:\Users\xiaoxi\Desktop\sxb_env\sxb\sxbweb\admin.py
:
from django.contrib import admin
from .models import ItemType, Item
@admin.register(ItemType)
class ItemTypeAdmin(admin.ModelAdmin):
list_display = ('id', 'type_name')
@admin.register(Item)
class ItemAdmin(admin.ModelAdmin):
list_display = ('title', 'id', 'author', 'item_type')
输入以下命令以启动调试用的Django本地服务:
(sxb_env) PS C:\Users\xiaoxi\Desktop\sxb_env\sxb> python .\manage.py runserver
现在可以看到如下的返回信息:
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
January 12, 2021 - 23:06:14
Django version 3.1.5, using settings 'sxb.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
打开 http://127.0.0.1:8000/admin 即可访问该应用管理页面。