Django部署Ubuntu18.04

准备工作

升级系统到最新版,执行后建议重启

sudo apt update
sudo apt upgrade -y

安装依赖

sudo apt install mysql-server -y #安装mysql
sudo apt install python3-dev python3-pip python-pip memcached -y #安装pip和memcached
sudo apt install virtualenv -y
sudo apt install nginx -y
sudo apt-get install python-dev default-libmysqlclient-dev #安装mysqlclient依赖

创建Python虚拟环境

cd ~
mkdir -p  python/env && cd python/env
virtualenv -p /usr/bin/python3 djangoblog
source djangoblog/bin/activate

安装第三方库

source ~/python/env/djangoblog/bin/activate
cd ~/python/DjangoBlog
pip install -Ur requirements.txt

配置MySQL数据库

初始化MySQL

sudo mysql_secure_installation

创建账号和数据库

mysql -uroot -p #进入mysql终端
CREATE USER 'djangoblog'@'localhost' IDENTIFIED BY 'DjAnGoBlOg123!@#';
CREATE DATABASE `djangoblog` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci */;
GRANT all ON djangoblog.* TO 'djangoblog'@'localhost';
FLUSH PRIVILEGES;
exit #退出

修改djangoblog配置

sudo vim /etc/mysql/conf.d/mysql.cnf
  • 添加如下内容
sql_mode=NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
  • 重启mysqld
sudo systemctl restart mysql

修改djangoblog配置

  • 修改DjangoBlog/settings.py中的DATABASES配置:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'djangoblog',
        'USER': 'djangoblog',
        'PASSWORD': 'DjAnGoBlOg123!@#',
        'HOST': 'localhost',
        'PORT': 3306,
        'OPTIONS': {'charset': 'utf8mb4'},
    }
}
  • 接下来开始执行数据库迁移,终端下执行:
python manage.py makemigrations
python manage.py migrate
# python manage.py createsuperuser #创建超级用户
# python manage.py static --no-input
# python manage.py compress --force
  • 下面可以尝试启动网站,终端下执行:
python manage.py  runserver

nginx配置

评论