Django
安装
pip install django
创建项目
django-admin startproject 项目名
__init__.py 说明JangoDemo 是一个Python包
settings.py 项目的配置文件
urls.py 进行url路由的配置
wsgi.py 服务器和Django交互的入口
manage.py 项目的管理文件
创建应用
python manage.py startapp 应用名
启动项目
python manage.py runserver
Model
创建实体类,生成迁移文件
from django.db import models
# Create your models here.
class BookInfo(models.Model):
"""图书信息"""
# 图书名称
b_title = models.CharField(max_length=20)
# 出版日期
b_pub_date = models.DateField()
# 后台更容易识别
def __str__(self):
return self.b_title
# 自定义表名
class Meta:
db_table = 'bookinfo'
# 一对多
class Hero(models.Model):
"""英雄"""
# 姓名
h_name = models.CharField(max_length=20)
# 属性名为 名称_id
h_book = models.ForeignKey('BookInfo',on_delete=models.CASCADE)
执行命令
# 生成表(默认使用的数据库 sqlite3)
python manage.py makemigrations
# 执行表
python manage.py migrate
后台管理
本地化
修改 语言 和 时区
# settings.py
# 语言默认英文
# LANGUAGE_CODE = 'en-us'
# 使用中文
LANGUAGE_CODE = 'zh-hans'
# 时区
# TIME_ZONE = 'UTC'
# 中国时间
TIME_ZONE = 'Asia/Shanghai'
创建管理员
python manage.py createsuperuser
# 按照提示输入用户名,电子邮箱,密码
# 启动项目
# 登录页面 http://localhost:8000/admin/login/
# 输入用户名及密码
注册模型类
# admin.py
from django.contrib import admin
from booktest.models import BookInfo,Hero
class BookInfoAdmin(admin.ModelAdmin):
# 显示的属性名称
list_display = ['id','b_title','b_pub_date']
class HeroAdmin(admin.ModelAdmin):
list_display = ['id','h_name','h_book_id']
# Register your models here.
admin.site.register(BookInfo,BookInfoAdmin)
admin.site.register(Hero,HeroAdmin)
配置 Mysql
项目
# 1.配置数据库信息
########################## settings.py
DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
'ENGINE': 'django.db.backends.mysql',
# 数据库名称
'NAME': 'hello',
# 用户名
'USER':'root',
# 密码
'PASSWORD':'root',
# ip
'HOST':'localhost',
# 端口
'PORT':3306,
'OPTIONS': {'isolation_level': None}
}
}
# 2.设置项目包初始文件
```python
########### __init__.py
import pymysql
pymysql.install_as_MySQLdb()
View
Sample
项目
######################## urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
# 包含项目的路径
path('booktest/',include('booktest.urls'))
]
应用
####################### booktest/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('index/',views.index),
]
################### booktest/views.py
from django.http import HttpResponse
def index(request):
return HttpResponse('index page')
模版
# 1.注册路由
################### booktest/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('hello/',views.hello)
]
# 2.在项目根目录下创建模版文件夹templates
# 3.在settings.py 文件中配置模版文件夹路径
################### settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# BASE_DIR 当前项目的绝对路径
'DIRS': [os.path.join(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',
],
},
},
]
# 4.接口逻辑代码
################### booktest/views.py
from django.shortcuts import render
def hello(request):
return render(request,'booktest/index.html')
# 5.页面代码
################### templates/booktest/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1>我是首页</h1>
</body>
</html>
传递参数
################### booktest/views.py
from django.urls import path
from . import views
def params_to_html(request):
# 传递参数到模版
return render(request,'booktest/template_index.html',{'content':'Hello World','list':list(range(1,10))})
################### templates/booktest/template_index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>模版</title>
</head>
<body>
<h1>我是一个模版</h1>
使用模版变量<br />
字典<br />
{{content}}
<br />
列表<br />
{{list}}
<ul>
{% for i in list %}
<li>{{ i }}</li>
{% endfor %}
</ul>
</body>
</html>
正则
############ booktest/urls.py
from django.urls import re_path
from . import views
urlpatterns = [
# 正则
# (\d+) 需要传递的id
re_path(r'^book_detail/(\d+)$',views.get_book_detail)
]
############ booktest/urls.py
def get_book_detail(request,bid):
# bid 传递过来的 id
pass
设置错误页面
################### settings.py
DEBUG = False
ALLOWED_HOSTS = ['*']
<!-- templates/404.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>找不到哦!</title>
</head>
<body>
<h1>我在哪里,我是谁?</h1>
</body>
</html>
设置静态文件路径及访问地址
# 1.创建静态文件夹
# 在项目根目录下创建文件夹 static,并分别建立三个子文件 js,css,images
# 2.在根目录下的设置文件settings.py中配置路径
######################## settings.py
# 静态文件访问地址
STATIC_URL = '/static/'
# 静态文件物理路径
STATICFILES_DIRS=[os.path.join(BASE_DIR,"static")]
在html里面使用动态的静态文件路径
<!DOCTYPE html>
<!--引入静态文件标签-->
{% load staticfiles %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>静态文件</title>
</head>
<body>
<img src="/static/images/mn.jpg" />
<img src="{% static 'images/mn.jpg' %}" />
</body>
</html>
中间件
# 在应用目录下创建文件 middleware.py
# 创建中间件
########################## booktest/middleware.py
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
class TestMiddleWare(MiddlewareMixin):
"""中间件测试类"""
def __init__(self,get_response=None):
super().__init__(get_response)
print("============ __init__ ============")
def process_request(self,request):
"""产生request对象之后,url匹配之前调用"""
print("============ process_request ============")
def process_view(self,request,view_func,*view_args,**view_kwargs):
"""url匹配之后,视图函数调用之前"""
print("============ process_view ============")
def process_response(self,request,response):
"""视图函数调用之后,内容返回浏览器之前"""
print("============ process_response ============")
return response
def process_exception(self,request,exception):
"""视图函数发生异常时调用"""
print("============ process_exception ============")
return HttpResponse(exception)
# 3.在settings.py文件中注册中间件
MIDDLEWARE = [
...
'booktest.middleware.TestMiddleWare',
]
上传文件
后台管理上传
## booktest/models.py
class PicTest(models.Model):
"""上传文件"""
# upload_to 图片上传后保存的位置
gpic = models.ImageField(upload_to='booktest')
## 注册 booktest/admin.py
admin.site.register(PicTest)
## 设置访问路径 settings.py
# 静态文件访问地址
STATIC_URL = '/static/'
# 静态文件物理路径
STATICFILES_DIRS=[os.path.join(BASE_DIR,"static")]
# 上传文件的存储位置
MEDIA_ROOT = os.path.join(BASE_DIR,"static/media")
用户上传
## booktest/urls.py
urlpatterns = [
path('upload_index/',views.show_upload),
path('upload_pic',views.upload_pic),
]
## booktest/views.py
def show_upload(request):
"""显示上传文件的页面"""
return render(request,"booktest/upload_index.html")
def upload_pic(request):
"""上传文件"""
# 1.获取上传图片
pic = request.FILES['some_file']
# 2.创建一个文件夹
save_path = "%s/booktest/%s"%(settings.BASE_DIR,pic.name)
print(save_path)
# 3.获取上传文件的内容,并上传到创建的文件夹中
with open(save_path,"wb") as f:
for content in pic.chunks():
f.write(content)
# 4.在数据库中保存上传记录
PicTest.objects.create(gpic="booktest/%s"%pic.name)
# 5.返回
return HttpResponseRedirect("/pic_index",{"pic_path","booktest/%s"%pic.name})
<!--templates/booktest/upload_index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传图片</title>
</head>
<body>
<form method="post" action="/upload_pic" enctype="multipart/form-data">
{% csrf_token %}
<input name="some_file" type="file"><br />
<input type="submit" value="提交">
</form>
</body>
</html>