# 安装依赖
yum -y install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel libffi-devel gcc
wget https://www.python.org/ftp/python/3.8.15/Python-3.8.15.tgz
tar xf Python-3.8.15.tar.xz
cd Python-3.8.15
./configure --prefix=/usr/local/python3
make && make install
# 删除旧软链接
rm -rf /usr/bin/python3
rm -rf /usr/bin/pip3
# 新添加软链接
ln -s /usr/local/python3/bin/python3.8 /usr/bin/python3
ln -s /usr/local/python3/bin/pip3.8 /usr/bin/pip3
cd ~
mkdir .pip
vi .pip/pip.conf
# 增加如下内容
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
[install]
trusted-host = pypi.tuna.tsinghua.edu.cn
pip3 install django
# 新版跟老版不太一样,需要自己设置软链接
ln -s /usr/local/python3/bin/django-admin /usr/bin/django-admin
django-admin startproject web
报错
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/usr/local/python3/lib/python3.8/site-packages/django/db/backends/base/base.py", line 282, in ensure_connection
...
File "/usr/local/python3/lib/python3.8/site-packages/django/db/backends/sqlite3/_functions.py", line 45, in register
create_deterministic_function("django_date_extract", 2, _sqlite_datetime_extract)
pysqlite3.dbapi2.NotSupportedError: deterministic=True requires SQLite 3.8.3 or higher
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/python3/lib/python3.8/threading.py", line 932, in _bootstrap_inner
...
File "/usr/local/python3/lib/python3.8/site-packages/django/db/backends/sqlite3/_functions.py", line 45, in register
create_deterministic_function("django_date_extract", 2, _sqlite_datetime_extract)
django.db.utils.NotSupportedError: deterministic=True requires SQLite 3.8.3 or higher
解决办法
pip3 install pysqlite3
pip3 install pysqlite3-binary
vim /usr/local/python3/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py
# 修改内容
# from sqlite3 import dbapi2 as Database (注释掉这段)
from pysqlite3 import dbapi2 as Database # 启用pysqlite3
# :wq 保存即可
再次运行
[root@hecs-33592 web]# python3 manage.py runserver 0.0.0.0:8000
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
November 24, 2022 - 09:16:47
Django version 4.1.3, using settings 'web.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
浏览器访问
报错了,修改ALLOWED_HOSTS
后面我们直接使用VSCode
进行项目的编辑与运行,有条件的同学可以考虑使用Pycharm
web
├── db.sqlite3
├── manage.py # 项目的管理,包括: 启动项目,创建app, 数据管理
└── web
├── asgi.py # 接收网络请求
├── __init__.py
├── settings.py # 项目配置(模板配置,数据库配置,注册app)
├── urls.py # url和函数的对应关系
└── wsgi.py # 接收网络请求
在 /root/python/web/web
下新增一个 views.py
文件
from django.http import HttpResponse
def index(req):
return HttpResponse('welcome to Django
')
配置/root/python/web/web
下的urls.py
文件
from django.contrib import admin
from django.urls import path
from . import views # 导入我们刚刚创建的views.py文件
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index), # 新增这一行,''为空表示默认访问 ip:端口
]
启动
cd /root/python/web/
python3 manage.py runserver 0.0.0.0:5900
浏览器访问测试
进入linux命令行,执行以下命令
[root@hecs-33592 web]# pwd
/root/python/web
[root@hecs-33592 web]# django-admin startapp blog
[root@hecs-33592 web]# ls
blog db.sqlite3 manage.py web
[root@hecs-33592 web]# tree blog/
blog/
├── admin.py
├── apps.py
├── __init__.py
├── migrations
│ └── __init__.py
├── models.py
├── tests.py
└── views.py
应用【blog】中各个目录作用:
修改/root/python/web/web
下的settings.py
编辑/root/python/web/blog
下的views.py
视图函数
from django.shortcuts import render
from django.http import HttpResponse
def index_app(req):
return HttpResponse('welcome to Django blog!')
编辑/root/python/web/web
下的urls.py
来指定访问路由
from django.contrib import admin
from django.urls import path
from blog.views import index_app
urlpatterns = [
path('admin/', admin.site.urls),
path('index_app/', index_app),
]
命令行启动Django应用
cd /root/python/web/
python3 manage.py runserver 0.0.0.0:5900
再来一个
编辑/root/python/web/blog
下的views.py
视图函数
from django.shortcuts import render
from django.http import HttpResponse
def user_list(request):
return HttpResponse("用户列表")
def index_app(req):
return HttpResponse('welcome to Django blog!
')
编辑/root/python/web/web
下的urls.py
来指定访问路由
from django.contrib import admin
from django.urls import path
from blog.views import index_app
from blog.views import user_list
urlpatterns = [
path('admin/', admin.site.urls),
path('index_app/', index_app),
path('user_list/', user_list),
]
为了使用HTML,这里开始引入templates模板
注意: 可以在app下创建templates
目录,也可以在主目录下创建templates
目录
接下来可以做个测试
编辑/root/python/web/blog
下的views.py
视图函数
from django.shortcuts import render
from django.http import HttpResponse
def user_list(request):
# 1.优先去项目的根目录下寻找
# 2.根据app的注册顺序去app的目录下templates下寻找
return render(request, "user_list.html")
编辑/root/python/web/blog/templates
下的user_list.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Documenttitle>
head>
<body>
<h1>用户列表h1>
body>
html>
编辑/root/python/web/templates
下的user_list.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Documenttitle>
head>
<body>
<h1>根目录,用户列表h1>
body>
html>
1.优先去项目的根目录
templates
下寻找
2.根据app
的注册顺序去项目app
的目录下的templates
下寻找
创建一个新的模板页面
编辑web
下的urls.py
from django.contrib import admin
from django.urls import path
from blog import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index_app/', views.index_app),
path('user_list/', views.user_list),
path('tpl/', views.tpl),
]
编辑APPblog
下的views.py
from django.shortcuts import render
from django.http import HttpResponse
def user_list(request):
# 1.优先去项目的根目录下寻找
# 2.根据app的注册顺序去app的目录下templates下寻找
return render(request, "user_list.html")
def index_app(req):
return HttpResponse('welcome to Django blog!
')
# 新增下面的内容
def tpl(request):
return render(request, "tpl.html")
在blog/templates
下新建tpl.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
head>
<body>
<h1>templates模板语法h1>
body>
html>
如果说我们从数据库中取到了数据,如何在
html
页面中进行展示呢,这里需要用到templates的基本语法
修改blog
下的views.py
def tpl(request):
name = "poker"
return render(request, "tpl.html", {"name":name})
修改blog/templates
下的tpl.html
<body>
<h1>templates模板语法h1>
<li>姓名: {{ name }}li>
body>
这样,
name
参数就被传到HTML页面中展示了出来
def tpl(request):
name = "poker"
roles_list = ['服务员1', '服务员2', '服务员3']
return render(request, "tpl.html", {"name":name, "roles_list":roles_list})
<body>
<h1>templates模板语法h1>
<li>姓名: {{ name }}li>
<li>服务员:{{ roles_list }}li>
<li>服务员:{{ roles_list.0 }}li>
<li>服务员:{{ roles_list.1 }}li>
<li>服务员:{{ roles_list.2 }}li>
body>
修改blog/templates
下的tpl.html
<div>
列表循环:
{% for item in roles_list %}
<span>{{ item }}span>
{% endfor %}
div>
修改blog
下的views.py
def tpl(request):
name = "poker"
roles_list = ['服务员1', '服务员2', '服务员3']
user_info = {"name": "张三", "age": 25, "sex": "男"}
return render(request, "tpl.html", {"name": name, "roles_list": roles_list, "user_info": user_info})
修改blog/templates
下的tpl.html
<div>
{{ user_info }}<br>
{{ user_info.name }}
{{ user_info.age }}
{{ user_info.sex }}
div>
修改blog/templates
下的tpl.html
获取值
values
<div>
{% for v in user_info.values %}
<li>{{ v }}li>
{% endfor %}
div>
获取键
keys
<div>
{% for k in user_info.keys %}
<li>{{ k }}li>
{% endfor %}
div>
获取键和值
items
<div>
{% for k,v in user_info.items %}
<li>{{ k }} = {{ v }}li>
{% endfor %}
div>
修改blog
下的views.py
def tpl(request):
name = "poker"
roles_list = ['服务员1', '服务员2', '服务员3']
user_info = {"name": "张三", "age": 25, "sex": "男"}
date_list = [
{"name": "张三", "age": 25, "sex": "男"},
{"name": "李四", "age": 18, "sex": "男"},
{"name": "王五", "age": 22, "sex": "女"},
]
return render(request, "tpl.html", {"name": name, "roles_list": roles_list, "user_info": user_info, "data_list":date_list})
修改blog/templates
下的tpl.html
<div>
{% for item in data_list %}
<div>{{ item.name }} {{ item.age }} {{ item.sex }}div>
{% endfor %}
div>
修改blog/templates
下的tpl.html
{% if name == "poker" %}
<h3>嘿嘿嘿h3>
{% elif name == "toker" %}
<h3>哈哈哈h3>
{% else %}
<h3>呵呵呵h3>
{% endif %}
先介绍这些常用的语法,其实还有很多的语法,感兴趣的可自行百度.
重定向: 浏览器向某个网站发送请求,网站返回给浏览器一个新的URL,浏览器去访问这个新的URL地址
修改blog
下的views.py
, 根据情况去掉下面代码的注释进行测试
# 导入 redirect 包
from django.shortcuts import render, redirect
...
# 增加新函数
def something(request):
# request 是一个对象,封装了用户发送过来的所有请求相关数据
# 1.[请求]获取请求的方式
print("用户请求的方式: " + request.method)
# 2.[请求]在URL上传递值, 例如: http://123.249.26.154:5900/something/?n1=1&n2=2
print(request.GET)
# 3.[请求]在请求体中提交数据,目前是空值
print(request.POST)
# 4.[响应]HttpResponse("返回内容"), 内容字符串内容返回给请求者
# return HttpResponse("返回内容")
# 5.[响应]读取HTML的内容 + 渲染(替换) => 字符串,返回给用户浏览器
# 需要在 blog/templates 下新建`something.html`
#return render(request, 'something.html', {"title": "hello"})
# 6.[响应] 让浏览器重定向到其他的页面
return redirect("http://www.baidu.com")
修改web/web/urls.py
,增加something
from django.contrib import admin
from django.urls import path
from blog import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index_app/', views.index_app),
path('user_list/', views.user_list),
path('tpl/', views.tpl),
path('something/', views.something),
]
修改blog
下的views.py
,新增login
函数
def login(request):
if request.method == "GET":
return render(request, "login.html")
# 如果是 POST 请求,获取用户提交的数据
print(request.POST)
username = request.POST.get("user")
password = request.POST.get("password")
if username == "poker" and password == "123":
return HttpResponse("登录成功")
#return HttpResponse("登录失败")
return render(request, "login.html", {"error_msg": "用户名或密码错误"})
修改web/web/urls.py
,增加login
from django.contrib import admin
from django.urls import path
from blog import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index_app/', views.index_app),
path('user_list/', views.user_list),
path('tpl/', views.tpl),
path('something/', views.something),
path('login/', views.login),
]
在blog/templates
下新建login.html
{% csrf_token %} 必须加上
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Documenttitle>
head>
<body>
<h1>用户登录h1>
<form method="post" action="/login/">
{% csrf_token %}
<input type="text" name="user", placeholder="用户名">
<input type="password" name="password", placeholder="密码">
<input type="submit" value="提交">
<span style="color: red;">{{ error_msg }}span>
form>
body>
html>
Django开发操作数据库更简单,内部提供了ORM框架
mysqlclient
直接安装可能会报错
解决办法
参考链接: https://blog.csdn.net/m0_67155975/article/details/123138225
yum -y install mysql-devel
yum -y install python-devel
pip3 install mysqlclient
ORM可以帮助我们做两件事:
create database mydb DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
DATABASES = {
'default':{
'ENGINE':'django.db.backends.mysql',
'NAME':'mydb',
'USER':'root',
'PASSWORD':'Syz123!@#',
'HOST':'127.0.0.1',
'PORT':'3306',
}
}
配置blog
下的models.py
会根据自定义的类创建跟app同名的表
from django.db import models
# Create your models here.
class UserInfo(models.Model):
name = models.CharField(max_length=20)
password = models.CharField(max_length=20)
age = models.IntegerField()
"""
create table UserInfo(
id bigint auto_increment primary key,
name varchar(20),
password varchar(20),
age int
)
"""
在服务器中项目根目录下执行命令
如果不想要某个表了,将class类注释后,重新执行下面的命令即可
python3 manage.py makemigrations
python3 manage.py migrate
注意: app需要提前注册
查看Mysql数据库
修改表的话,如果原表中存有数据,此时如果增加一个新的列,需要设定一个默认值
age = models.IntegerField(default=2)
data = models.IntegerField(null=True, blank=True)
修改blog
下的views.py
from blog.models import UserInfo
...
def orm(request):
# 新建数据
UserInfo.objects.create(name="poker", password="123", age=25)
UserInfo.objects.create(name="roker", password="456", age=30)
return HttpResponse("成功")
修改web/web/urls.py
,增加orm
from django.contrib import admin
from django.urls import path
from blog import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index_app/', views.index_app),
path('user_list/', views.user_list),
path('tpl/', views.tpl),
path('something/', views.something),
path('login/', views.login),
path('orm/', views.orm),
]
# 删除数据
UserInfo.objects.filter(id=2).delete()
# 删除表中所有数据
UserInfo.objects.all().delete()
data_list = UserInfo.objects.all()
print(data_list)
for obj in data_list:
print(obj.id, obj.name, obj.password, obj.age)
UserInfo.objects.filter(name="roker").update(age=35)
修改web/web/urls.py
,增加info/list
from django.contrib import admin
from django.urls import path
from blog import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index_app/', views.index_app),
path('user_list/', views.user_list),
path('tpl/', views.tpl),
path('something/', views.something),
path('login/', views.login),
path('orm/', views.orm),
path('info/list/', views.info_list)
]
修改blog
下的views.py
from blog.models import UserInfo
...
def info_list(request):
data_list = UserInfo.objects.all()
return render(request, "info_list.html", {"data_list": data_list})
在blog/templates
下新增info_list.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Documenttitle>
head>
<body>
<table border="1">
<thead>
<tr>
<th>IDth>
<th>姓名th>
<th>密码th>
<th>年龄th>
tr>
thead>
<tbody>
{% for obj in data_list %}
<tr>
<td>{{ obj.id }}td>
<td>{{ obj.name }}td>
<td>{{ obj.password }}td>
<td>{{ obj.age }}td>
tr>
{% endfor %}
tbody>
table>
body>
html>
修改web/web/urls.py
,增加info/list
from django.contrib import admin
from django.urls import path
from blog import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index_app/', views.index_app),
path('user_list/', views.user_list),
path('tpl/', views.tpl),
path('something/', views.something),
path('login/', views.login),
path('orm/', views.orm),
path('info/list/', views.info_list),
path('info/add/', views.info_add),
]
修改blog
下的views.py
def info_add(request):
if request.method == "GET":
return render(request, 'info_add.html')
# 获取用户提交的数据
name = request.POST.get("name")
password = request.POST.get("password")
age = request.POST.get("age")
# 添加到数据库
UserInfo.objects.create(name=name, password=password, age=age)
# 自动跳转
return redirect("/info/list/")
在blog/templates
下新增info_add.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Documenttitle>
head>
<body>
<form action="/info/add/" method="post">
{% csrf_token %}
<input type="text" name="name" placeholder="用户名">
<input type="text" name="password" placeholder="密码">
<input type="text" name="age" placeholder="年龄">
<input type="submit" value="提交">
form>
body>
html>
浏览器访问
点击"提交"
在info/list
页面增加"添加"按钮
修改blog/templates
下info_list.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Documenttitle>
head>
<body>
<a href="/info/add">添加a>
<table border="1">
<thead>
<tr>
<th>IDth>
<th>姓名th>
<th>密码th>
<th>年龄th>
tr>
thead>
<tbody>
{% for obj in data_list %}
<tr>
<td>{{ obj.id }}td>
<td>{{ obj.name }}td>
<td>{{ obj.password }}td>
<td>{{ obj.age }}td>
tr>
{% endfor %}
tbody>
table>
body>
html>
修改web/web/urls.py
,增加info/list
from django.contrib import admin
from django.urls import path
from blog import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index_app/', views.index_app),
path('user_list/', views.user_list),
path('tpl/', views.tpl),
path('something/', views.something),
path('login/', views.login),
path('orm/', views.orm),
path('info/list/', views.info_list),
path('info/add/', views.info_add),
path('info/delete/', views.info_delete)
]
修改blog
下的views.py
def info_delete(request):
nid = request.GET.get("nid")
UserInfo.objects.filter(id=nid).delete()
return redirect("/info/list/")
修改blog/templates
下的info_list.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Documenttitle>
head>
<body>
<a href="/info/add">添加a>
<table border="1">
<thead>
<tr>
<th>IDth>
<th>姓名th>
<th>密码th>
<th>年龄th>
<th>操作th>
tr>
thead>
<tbody>
{% for obj in data_list %}
<tr>
<td>{{ obj.id }}td>
<td>{{ obj.name }}td>
<td>{{ obj.password }}td>
<td>{{ obj.age }}td>
<td>
<a href="/info/delete?nid={{ obj.id }}">删除a>
td>
tr>
{% endfor %}
tbody>
table>
body>
html>