Installation Django-3.2.10 on CentOS 7.9
一、Installation Django-3.2.10 on CentOS 7.9
地址
二、安装 django
先得安装python
python3
python3 -V
pip3 -V
pip3 install django==3.2.10
三、创建项目
mkdir -p /opt/django/src
cd /opt/django/src
django-admin startproject mysite
# -bash: django-admin: command not found
find / -name django-admin.py
# /usr/local/python3/bin/django-admin.py
# /usr/local/python3/lib/python3.9/site-packages/django/bin/django-admin.py
四、添加环境变量
vim /etc/profile
export PATH=$PATH:/usr/local/python3/bin
source /etc/profile
五、启动 django
找不到sqlite3
ModuleNotFoundError: No module named '_sqlite3'
sqlite3已经升级后,还是报错
django.db.utils.NotSupportedError: deterministic=True requires SQLite 3.8.3 or higher
django.core.exceptions.ImproperlyConfigured: SQLite 3.9.0 or later is required (found 3.8.11.1).
怎么都对不上,后来降低版本重新安装,来解决此问题。
这是django中目前的所有版本,安装的2.2.28中最后一个版本。
wget https://www.python.org/ftp/python/3.8.3/Python-3.8.3.tgz
wget http://sqlite.org/2015/sqlite-autoconf-3081101.tar.gz
pip3 install django=2.2.28
# 操作简单傻瓜式安装
# 只需把对应版本修改,即可
# sqltie3是一个小型数据库,在公司大部分情况还是会使用MySQL的
CentOS 7.9 安装 Python-3.9.5:https://www.cnblogs.com/huaxiayuyi/p/16760576.html
CnetOS 7.9 安装 sqlite3:https://www.cnblogs.com/huaxiayuyi/p/16770739.html
注意:看好版本在安装
六、解决方法
三种解决方法
-
升级系统 sqlite 版本(已试,不好使,各种问题)
-
降低 django 版本(公司项目,不可能降版本,放弃))
-
使用其他库替代系统的 sqlite(已试,挺方便)
使用第三种解决方法
# 安装
pip3 install pysqlite3
pip3 install pysqlite3-binary
修改 db 代码导入库()
vim /usr/local/python3/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py
# from sqlite3 import dbapi2 as Database
from pysqlite3 import dbapi2 as Database
注意:第三种方案修改源码其实不推荐
七、在浏览器访问
# 获取私有地址
hostname -I
python3 manage.py runserver IP:8000
拿着公网地址访问
DisallowedHost at /
Invalid HTTP_HOST header: '114.116...:8000'. You may need to add '114.116...' to ALLOWED_HOSTS.
配置settings.py
# 防止黑客入侵,只允许列表中的IP地址访问
# * 所有主机都可以访问
vim mysite/settings.py
ALLOWED_HOSTS = ['*']
八、防火墙放行
# 关闭防火墙
systemctl stop firewalld
# 开放8000端口命令
firewall-cmd --zone=public --add-port=8000/tcp --permanent
# 配置立即生效
firewall-cmd --reload
云服务器配置安全组8000放行
九、安装 virtualenv
# 更新pip3至最新版本(可省略)
pip3 install --upgrade pip
# 安装virtualenv
pip3 install virtualenv
# 建立软链接,方便在终端中直接使用virtualenv
ln -s /usr/local/python3/bin/virtualenv /usr/bin/virtualenv
virtualenv --version
# virtualenv 20.16.5 from /usr/local/python3/lib/python3.9/site-packages/virtualenv/__init__.py
十、创建虚拟环境
创建目录xyzweb,创建虚拟文件夹名字env,自定义名字,虚拟环境有利于版本隔离,每次都需下载所需依赖,但它是个干净的,纯净的虚拟环境。
激活虚拟环境
source env/bin/activate
退出虚拟环境
deactivate
十一、在虚拟环境安装 django
[root@ecs-65685 ~]# mkdir -p /opt/django/src/pyweb
[root@ecs-65685 ~]# cd /opt/django/src/pyweb
[root@ecs-65685 pyweb]# virtualenv --python=/usr/bin/python3 env
created virtual environment CPython3.9.5.final.0-64 in 572ms
creator CPython3Posix(dest=/opt/django/src/pyweb/env, clear=False, no_vcs_ignore=False, global=False)
seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/root/.local/share/virtualenv)
added seed packages: pip==22.2.2, setuptools==65.3.0, wheel==0.37.1
activators BashActivator,CShellActivator,FishActivator,NushellActivator,PowerShellActivator,PythonActivator
[root@ecs-65685 pyweb]# source env/bin/activate
(env) [root@ecs-65685 pyweb]# pip3 install django==3.2.10
Collecting django==3.2.10
Using cached Django-3.2.10-py3-none-any.whl (7.9 MB)
Collecting asgiref<4,>=3.3.2
Using cached asgiref-3.5.2-py3-none-any.whl (22 kB)
Collecting sqlparse>=0.2.2
Using cached sqlparse-0.4.3-py3-none-any.whl (42 kB)
Collecting pytz
Using cached pytz-2022.4-py2.py3-none-any.whl (500 kB)
Installing collected packages: pytz, sqlparse, asgiref, django
Successfully installed asgiref-3.5.2 django-3.2.10 pytz-2022.4 sqlparse-0.4.3
(env) [root@ecs-65685 pyweb]# pip3 list
Package Version
---------- -------
asgiref 3.5.2
Django 3.2.10
pip 22.2.2
pytz 2022.4
setuptools 65.3.0
sqlparse 0.4.3
wheel 0.37.1
(env) [root@ecs-65685 pyweb]# django-admin startproject mysite
(env) [root@ecs-65685 pyweb]# ls
env mysite
(env) [root@ecs-65685 pyweb]# cd mysite
(env) [root@ecs-65685 mysite]# vim mysite/settings.py
(env) [root@ecs-65685 mysite]# python3 manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
October 09, 2022 - 15:17:26
Django version 3.2.10, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
^C(env) [root@ecs-65685 mysite]#
注释掉sqlite3,免得报错,回头用MySQL
vim mysite/settings.py
十二、创建应用
1 创建目录
mkdir common_static
mkdir templates
2 配置settings.py
vim /opt/django/src/pyweb/mysite/mysite/settings.py
# 允许所及主机访问
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 注册app应用
'app'
]
# TEMPLATES的DIRS里添加模板路径 'DIRS': [BASE_DIR / 'templates'],
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': BASE_DIR / 'db.sqlite3',
# }
#}
# 使用MySQL数据库
# 记得创建数据库,django不会帮你创建
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'xyzweb',
'USER':'root',
'PASSWORD':'...',
'HOST':'114.116...',
'PORT':3306,
'CHARSET':'utf8'
}
}
# 配置静态文件夹的存放目录
# css js img
import os
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'common_static'),
)
3 新建 index
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<h5>Hello Django!!!</h5>
</body>
</html>
4 路由跳转
vim mysite/urls.py
from django.contrib import admin
from django.urls import path
from app import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index', views.index),
]
5 编写视图函数
vim app/views.py
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, 'index.html')
6 导入MySQL数据库并安装
vim app/__init__.py
import pymysql
pymysql.install_as_MySQLdb()
7 目录结构
[root@ecs-65685 mysite]# pwd
/opt/django/src/pyweb/mysite
[root@ecs-65685 mysite]# tree
├── app
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── common_static
├── manage.py
├── mysite
│ ├── asgi.py
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── templates
└── index.html
8 启动 django
python3 manage.py runserver 192.168...:8000
浏览器访问 IP:8000
十三、配合MySQL使用
1 定义模型
vim app/models.py
class AppInfo(models.Model):
nid = models.AutoField(primary_key = True)
app_name = models.CharField(verbose_name = "应用名", max_length = 32)
2 执行数据迁移同步命令
python3 manage.py makemigrations
python3 manage.py migrate
Installation MySQL-5.7.35 on CentOS 7.9:https://www.cnblogs.com/huaxiayuyi/p/16758720.html
3 视图获取数据
vim app/views.py
from django.shortcuts import render
from app import models
# Create your views here.
def index(request):
queryset = models.AppInfo.objects.all()
return render(request, 'index.html', locals())
4 模板渲染数据
vim templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<h5>Hello Django !!!</h5>
{% for app in queryset%}
<p>{{ app.nid}}-{{app.app_name}}</p>
{% endfor %}
</body>
</html>
5 启动项目
python3 manage.py runserver 192.168...:8000
浏览器访问 IP:8000
注意:防火墙