Web框架Django管理页面使用
1.SQLite管理员账号创建
SQLite 是 Django 默认的数据库体量上类似与 Apache Derby
,配置信息如下:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
makemigrations
为模型的改变生成迁移文件,migrate
实现应用数据库迁移,切换数据库或者添加新的module
后要执行以上命令:
python .\manage.py migrate
否则创建管理员账号时会报错no such table: auth_user
当然,未创建admin
账号就登录同样报这个错:
OperationalError at /admin/login/
no such table: auth_user
# 创建管理员账号 admin
python .\manage.py createsuperuser
# 输入管理员账号名称
Username (leave blank to use 'administrator'): admin_test
# 输入Email地址
Email address: admin_test@example.com
# 输入密码
Password:
Password (again):
The password is too similar to the username.
Bypass password validation and create user anyway? [y/N]: y
# 创建成功
Superuser created successfully.
页面登录http://host:port/admin/
输入账号名称和密码登录:
2.GreenPlum管理页面使用
2.1 数据库配置及初始化
Django 支持许多不同的数据库服务器,官方支持 PostgreSQL、MariaDB、MySQL、Oracle 和 SQLite。其他 DataBase Bindings 信息可以查看官网,这里仅以 PostgreSQL 的孪生兄弟 GreenPlum
数据库举例,也算是测试对 GP 数据库的支持情况。ENGINE
用的也是postgresql
的,其他信息如下:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'algorithmcenter',
'USER': 'xxxx',
'PASSWORD': 'xxxx',
'HOST': 'hostname',
'PORT': '5432',
}
}
使用 PostgreSQL,需要 psycopg2 包,使用 GreenPlum 同样是需要的,安装 psycopg2-binary
命令如下:
# 安装命令
pip3 install psycopg2-binary
# 安装过程
Collecting psycopg2-binary
Downloading psycopg2_binary-2.9.3-cp38-cp38-win_amd64.whl (1.1 MB)
|████████████████████████████████| 1.1 MB 21 kB/s
Installing collected packages: psycopg2-binary
Successfully installed psycopg2-binary-2.9.3
migrate
时报错:
django.db.utils.IntegrityError:
UNIQUE index must contain all columns in the distribution key of relation "django_content_type"
由于GP
数据库跟PG
数据库还是存在一些语法不一致的地方,这里将SQLite
里的10
张表同步到GP
并创建auth_user
表id
字段的自增序列:
CREATE SEQUENCE greenplum_sequence START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1;
ALTER TABLE auth_user ALTER COLUMN ID
SET DEFAULT nextval( 'greenplum_sequence' );
修改django_session
表的expire_date
字段格式由text 改为 timestamp
否则登录时报错。
2.2 管理员账号创建
# 账户创建
python .\manage.py createsuperuser
Username (leave blank to use 'administrator'): test
Email address: test@qq.com
Password:
Password (again):
The password is too similar to the username.
This password is too short. It must contain at least 8 characters.
This password is too common.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.
登录成功页面不再贴出。
2.3 Django数据库API使用
简单测试,更多API查看 官网。
from xxxx.models import Choice, Question
Question.objects.all()
from django.utils import timezone
q = Question(question_text="What's new?", pub_date=timezone.now())
q.save()
q.id
q.question_text
q.pub_date
q.question_text = "What's up?"
q.save()
Question.objects.all()
2.4 应用添加
在应用文件夹下的admin.py
文件内添加注册代码:
# Register your models here.
from .models import Question
admin.site.register(Question)
新增数据:
修改数据:
3.总结
Django 对 GreenPlum 数据库的支持不好,几乎不可用,可以非官方支持的数据库可放弃使用其数据库 API。