Django后台admin使用SimpleUi
为了更美观,使用方便在Django admin的基础上引入了simpleui,一起分享如何简单利用simpleui做出更美观的Django admin后台:
- 环境准备
- 引入simpleui
- 修改simple自定义模板
演示请点链接
演示网址
教程
目录
参考
知乎文案
准备环境
安装MySQL
wget https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm
rpm -ivh mysql80-community-release-el7-3.noarch.rpm
yum -y install mysql-community-server
systemctl start mysqld
cat /var/log/mysql.log |grep password
alter user root@localhost identified by '你的密码'
create database django default charset utf8;
安装Redis
yum -y install gcc-c++
wget https://download.redis.io/releases/redis-6.0.8.tar.gz
tar xzf redis-6.0.8.tar.gz
cd redis-6.0.8
make && make install
注释掉以下内容
路径:redis-6.0.8/utils/install_server.sh
脚本安装
sh ./install _server.sh
直接回车 默认为6379端口 直接回车 配置文件默认路径/etc/redis/6379.conf 直接回车 日志默认路径/var/log/redis_6379.log 直接回车 数据库目录文件 /var/lib/redis/6379
redis添加密码
vim /etc/redis/6379.conf … requirepass 123456 …
redis杀掉重新启动
redis-cli shutdown
redis-server /etc/redis/6379.conf
安装Nginx
wget https://nginx.org/download/nginx-1.20.1.tar.gz
yum install -y pcre-devel pcre zlib zlib-devel openssl openssl-devel wget gcc gcc-c++ unzip
useradd -s /sbin/nologin nginx
tar -xvf nginx-1.20.1.tar.gz
cd nginx-1.20.1/
sed -i '49s/nginx/Microsoft-IIS/' src/http/ngx_http_header_filter_module.c
sed -i '50s/: /: Microsoft-IIS/' src/http/ngx_http_header_filter_module.c
sed -i '51s/: /: Microsoft-IIS/' src/http/ngx_http_header_filter_module.c
./configure --user=nginx --group=nginx --prefix=/opt/nginx --with-http_ssl_module --with-http_stub_status_module --with-stream --with-http_realip_module --with-http_realip_module
make && make install
cp -r /opt/nginx/sbin/nginx /usr/sbin/nginx
mkdir /opt/nginx/conf.d
mv /opt/nginx/conf/nginx.conf /opt/nginx/conf/nginx.bak.conf
修改 nginx 配置文件
vim /opt/nginx/conf/nginx.conf
worker_processes auto;
error_log logs/error.log error;
pid logs/nginx.pid;
events {
worker_connections 65535;
multi_accept on;
}
http {
include mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log logs/access.log main;
keepalive_timeout 60;
add_header Access-Control-Allow-Origin '*';
add_header Access-Control-Max-Age '3628800';
add_header Access-Control-Allow-Credentials 'true';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
add_header Access-Control-Allow-Methods 'GET,POST,PUT,OPTIONS';
underscores_in_headers on;
client_header_buffer_size 32k;
client_body_buffer_size 20m;
client_max_body_size 120M;
client_header_timeout 1m;
client_body_timeout 1m;
proxy_connect_timeout 600;
proxy_read_timeout 600;
proxy_send_timeout 600;
large_client_header_buffers 4 32k;
fastcgi_buffers 4 128k;
fastcgi_buffer_size 128k;
fastcgi_busy_buffers_size 256k;
server_tokens off;
tcp_nopush on;
tcp_nodelay on;
sendfile on;
gzip on;
gzip_vary on;
gzip_min_length 1k;
gzip_buffers 8 32k;
gzip_http_version 1.1;
gzip_comp_level 6;
gzip_proxied any;
gzip_types application/javascript application/json text/css image/png;
real_ip_header X-Real-IP;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
include /opt/nginx/conf.d/*.conf;
}
创建一个django.conf(/opt/nginx/conf.d/django.conf)
server {
listen 80;
server_name localhost;
location / {
include uwsgi_params;
uwsgi_pass 127.0.0.1:3210;
uwsgi_read_timeout 180s;
uwsgi_connect_timeout 180s;
uwsgi_send_timeout 180s;
index index.html index.htm;
}
location /static {
expires 30d;
autoindex on;
add_header Cache-Control private;
alias /opt/app/static/;
}
}
##注: 先不要启动nginx
创建一个Django项目
yum install python3-devel mysql-devel libcurl-devel
mkdir /opt/app
python3 -m venv /opt/app/venv
source /opt/app/venv/bin/activate
pip install django
pip simpleui
pip3 install django_redis
pip3 install mysqlclient
pip install django-cors-headers
django-admin startproject webapp
安装Uwsgi
pip install uwsgi
添加uwsgi文件 到项目下
vim /opt/app/webapp/webapp/uwsgi.ini
[uwsgi]
socket = 127.0.0.1:8871
chdir = /opt/app
module = webapp.wsgi
master = true
processes = 4
enable-threads = true
vacuum = true
max-requests = 5000
harakiri = 180
socket-timeout = 180
pidfile = app.wsgi.pid
daemonize =/var/log/uwsgi.log
env = LANG=en_US.UTF-8
启动命令
uwsgi --ini uwsgi
uwsgi --reload uwsig
uwsgi --reload app.wsgi.pid
修改配置文件引入SimpleUI
1. 修改Django 项目 setting.py文件(/opt/app/webapp/webapp/setting.py)
INSTALLED_APPS = [
'simpleui',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
...
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME':'django',
'HOST':'127.0.0.1',
'USER':'root',
'PASSWORD':'qweasd#.a434',
'PORT':'3306',
}
}
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"PASSWORD":'123456',
"SERIALIZER": "django_redis.serializers.json.JSONSerializer",
}
}
}
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
)
CORS_ALLOW_HEADERS = (
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
)
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_TZ = False
DEBUG = True
STATIC_ROOT = os.path.join(BASE_DIR, "static")
SIMPLEUI_STATIC_OFFLINE = True
2. 收集静态资源
cd /opt/app/webapp
python manage.py collectstatic
3.启动测试
cd /opt/app/webapp
python manager.py runserver 0.0.0.0:80
显示成功页面 ---- 显示中文
4. admin模块进行数据库初始化以及创建超级用户
python manage.py migrate
python manage.py createsuperuser
5. 检查simpleui是否正确引入
http://127.0.0.1:8000/admin 使用admin账户登录确认是否生效
创建一个APP
python manage.py startapp myapp
1. 添加到注册中心
vim /opt/app/webapp/webapp/setting.py
INSTALLED_APPS = [
'simpleui',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
]
2. 添加app的模型model
vim /opt/app/webapp/myapp/models.py
from django.db import models
import django.utils.timezone as timezone
class job_detail(models.Model):
JOB_TYPE_STATUS_GP = '01'
JOB_TYPE_STATUS_DEFAULT = '02'
JOB_TYPE_STATUS_CHOICES = (
(JOB_TYPE_STATUS_GP, 'Greenplum函数'),
(JOB_TYPE_STATUS_DEFAULT, '其他'),
)
CREATED_BY = models.CharField('创建人',max_length=32)
CREATED_TIME = models.DateTimeField('创建时间',default=timezone.now)
UPDATED_BY = models.CharField('更新人',max_length=32)
UPDATED_TIME = models.DateTimeField('更新时间',default=timezone.now)
JOB_TYPE = models.CharField('任务类型',max_length=32,
choices=JOB_TYPE_STATUS_CHOICES,
default=JOB_TYPE_STATUS_DEFAULT
)
JOB_NAME = models.CharField('任务名称',max_length=128)
JOB_COMMENT = models.TextField()('任务描述',max_length=128)
IN_PARA = models.CharField('输入参数定义',max_length=32)
IN_PARA_COMMENT = models.TextField()('输入参数描述',max_length=1024)
OUT_PARA = models.CharField('输出参数定义',max_length=32)
OUT_PARA_COMMENT = models.TextField()('输出参数描述',max_length=1024)
VERSION = models.CharField('版本号',max_length=32)
IS_DELETE = models.CharField('是否删除',max_length=1, default='N')
PRO_STATUS = models.CharField('发布状态',max_length=1,default='N')
3. 执行数据库迁移
python manage.py makemigrations
python manage.py migrate
4. 修改myapp/admin.py文件 注册到admin后台以及job_detail 内容的显示
vim /opt/app/webapp/myapp/admin.py
from django.contrib import admi
from myapp.models import job_detail
admin.site.site_header = '项目管理'
admin.site.site_title = '管理系统'
admin.site.index_title = u'管理系统
@admin.register(job_detail)
class job_detail(admin.ModelAdmin):
list_display = ('JOB_TYPE', 'JOB_NAME','JOB_COMMENT',
'IN_PARA','IN_PARA_COMMENT',
'OUT_PARA','OUT_PARA_COMMENT')
list_display_links = ('JOB_NAME',)
list_filter = ('JOB_TYPE', 'CREATED_TIME',)
list_per_page = 10
list_editable = ('IN_PARA_COMMENT',)
ordering = ('-CREATED_TIME',)
search_fields = ('JOB_NAME',)
actions = ['custom_button','upload_file']
fieldsets=(
('基本信息',{
'fields': ('JOB_TYPE', 'JOB_NAME','JOB_COMMENT',
'IN_PARA','IN_PARA_COMMENT',
'OUT_PARA','OUT_PARA_COMMENT')
}),
('STATUS',{
'fields': ('PRO_STATUS',)
}),
('参数描述', {
'fields': ('REQUIREMENTS2',)
}),
('任务描述', {
'fields': ('JOB_COMMENT','KIDS')
}),
)
def custom_button(self,request,queryset):
response = HttpResponse(content_type='text/csv',charset='GBK')
time_now = time.strftime('%Y%m%d')
filename = 'job_detail'+time_now
response['Content-Disposition'] = f'attachment; filename="{filename}.csv"'
writer = csv.writer(response)
writer.writerow(["创建人","任务描述","xxxx"...])
for i in queryset.values():
writer.writerow([i['CREATED_BY'],i['JOB_TYPE'],i['JOB_NAME']....])
return response
custom_button.short_description='导出数据'
custom_button.icon='fas fa-audio-description'
custom_button.style='color:black;'
custom_button.type='info'
def upload_file(self, request,queryset):
upload= request.FILES['upload']
print(upload)
upload_file.short_description = '上传数据'
upload_file.type = 'success'
upload_file.icon = 'el-icon-upload'
upload_file.enable = True
upload_file.layer = {
'params': [{
'type': 'file',
'key': 'upload',
'label': 'CSV文件'
}]
readonly_fields=("CREATED_BY",'CREATED_TIME','UPDATED_BY','UPDATED_TIME',
5. 修改SimpleUI自定义菜单栏(修改项目 setting.py)
#在文件末尾添加
SIMPLEUI_CONFIG = {
'system_keep': False,
'menu_display': ['任务管理', '信息管理','网站管理', '认证和授权'],
'dynamic': True,
'menus': [{
'app': 'myapp',
'name': '项目管理',
'icon': 'fab fa-app-store-ios',
'models': [{
'name': 'JOB',
'icon': 'fa fa-user',
'url': 'myapp/job_detail/'
}, {
'name': 'XXXXXXX',
'icon': 'el-icon-video-camera-solid',
'url': 'myapp/event/',
}]},
{
'app': 'xxx',
'name': '网站管理',
'icon': 'fa fa-th-list',
'models': [{
'name': 'XXXX',
'icon': 'el-icon-message-solid',
'url': 'XXX/XXXX/'
}, {
'name': 'OKOK',
'icon': 'el-icon-picture',
'url': 'XXXXX'
}
]},
{
'app': 'auth',
'name': '认证和授权',
'icon': 'fas fa-shield-alt',
'models': [{
'name': '用户',
'icon': 'far fa-user',
'url': 'auth/user/'
}, {
'name': '组',
'icon': 'fas fa-users-cog',
'url': 'auth/group/',
}]
}]
}
6. 测试是否菜单栏实现
python manager.py runserver 0.0.0.0:80
http://127.0.0.1:80/admin
最后:项目上线启动
#启动nginx
nginx
uwsgi --ini uwsgi.ini
|