使用Django快速搭建简单的数据管理后台
概述
需求描述:
数据表已建好,能可视化操作增删改查,避免直接操作数据库
简版的管理系统
环境
- Windows 10 x64
- Python 3.6.3 (Anaconda)
- Django 2.0.1
- MySQL 5.6.11-log
安装Django
pip install django
安装python-mysql
pip install mysqlclient
创建项目
django-admin startproject myproject
创建应用模块
cd myproject
python manage.py startapp myapp
配置数据库连接信息
#settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'testdb',
'USER': 'root',
'PASSWORD': '123456',
'HOST': 'localhost',
'PORT': '3306',
}
}
创建超级用户
python manage.py createsuperuser
启动应用
python manage.py runserver #默认8000
#python manage.py runserver 9999
装载应用模块
#settings.py
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',#添加到末尾
]
数据库反向生成Model
python manage.py inspectdb > myapp/models.py
注册Model
# myapp/admin.py
from django.contrib import admin
from myapp.models import Post
# Register your models here.
admin.site.register(Post)
解决Django在处理MySQL中BIT类型当做TextField处理问题
安装django_mysql模块
pip install django_mysql
# myapp/models.py
#引入django_mysql模块
from django_mysql.models import Bit1BooleanField
# myapp/models.py
将
models.TextField(blank=True, null=True) # This field type is a guess.
或
models.TextField() # This field type is a guess.
批量替换为 Bit1BooleanField(default=False)
关闭调试模式
# settings.py
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
# Must set settings.ALLOWED_HOSTS if DEBUG is False
ALLOWED_HOSTS = ['localhost','127.0.0.1','example.com']
静态资源访问处理
静态资源目录配置
# settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static') #新增配置
静态资源访问地址配置
# urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
收集应用所有静态文件至项目static目录下
python manage.py collectstatic
国际化处理
# settings.py
# 语言
#LANGUAGE_CODE = 'zh-cn'
LANGUAGE_CODE = 'zh-Hans'
# 时区
TIME_ZONE = 'Asia/Shanghai'
USE_TZ = True
页面表单标签中文显示
#models.py
class Post(models.Model):
title = models.CharField('标题', max_length=100)
memo = models.TextField('备注')
publish_date = models.DateTimeField('发表时间')
class Meta:
verbose_name = '文章'
verbose_name_plural = '文章'
ordering = ['publish_date']
def __unicode__(self):
return self.title
其他命令
#同步数据库(可将model改动同步到数据库)
python manage.py makemigrations
python manage.py migrate
#清空数据库
python manage.py flush
# 修改 用户密码可以用:
python manage.py changepassword username
#导出数据 导入数据
python manage.py dumpdata appname > appname.json
python manage.py loaddata appname.json
#Django 项目环境终端
python manage.py shell
#数据库命令行
python manage.py dbshell
参考资料