个人主页:丷从心·
系列专栏:Django
MVC与MTV
MVC设计模式
文章来源:https://www.toymoban.com/news/detail-860714.html
MTV设计模式
文章来源地址https://www.toymoban.com/news/detail-860714.html
Django下载
pip install django==2.2.5
Django工程创建与运行
创建工程
django-admin startproject book_manager
运行工程
python manage.py runserver
子应用创建与注册安装
创建子应用
python manage.py startapp book
注册安装子应用
- 配置
settings.py
中的INSTALLED_APPS
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'book.apps.BookConfig',
]
数据模型
ORM框架
- 配置
models.py
from django.db import models
# Create your models here.
# 书籍信息表
class BookInfo(models.Model):
name = models.CharField(max_length=10, verbose_name='书籍名称')
pub_date = models.DateField(null=True, verbose_name='出版日期')
read_count = models.IntegerField(default=0, verbose_name='阅读量')
comment_count = models.IntegerField(default=0, verbose_name='评论量')
is_delete = models.BooleanField(default=False, verbose_name='是否删除')
def __str__(self):
return self.name
class Meta:
db_table = 'book_info'
verbose_name = '书籍信息管理'
verbose_name_plural = verbose_name
# 人物信息表
class PersonInfo(models.Model):
GENDER_CHOICES = (
(0, 'male'),
(1, 'female')
)
name = models.CharField(max_length=10, verbose_name='人物名称')
gender = models.SmallIntegerField(choices=GENDER_CHOICES, default=0, verbose_name='人物性别')
description = models.CharField(max_length=100, null=True, verbose_name='人物描述')
book = models.ForeignKey(BookInfo, on_delete=models.CASCADE, verbose_name='人物所属书籍')
is_delete = models.BooleanField(default=False, verbose_name='是否删除')
def __str__(self):
return self.name
class Meta:
db_table = 'person_info'
verbose_name = '人物信息管理'
verbose_name_plural = verbose_name
模型迁移
-
Tools
->Run manage.py Task
makemigrations
migrate
Admin站点
修改语言和时区
- 配置
settings.py
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
设置管理员账号密码
-
Tools
->Run manage.py Task
createsuperuser
模型注册
- 配置
admin.py
from django.contrib import admin
# Register your models here.
from .models import BookInfo, PersonInfo
admin.site.register(BookInfo)
admin.site.register(PersonInfo)
显示对象名称
from django.db import models
# Create your models here.
# 书籍信息表
class BookInfo(models.Model):
name = models.CharField(max_length=10)
def __str__(self):
return self.name
# 人物信息表
class PersonInfo(models.Model):
name = models.CharField(max_length=10)
gender = models.BooleanField()
book = models.ForeignKey(BookInfo, on_delete=models.CASCADE)
def __str__(self):
return self.name
模型显示中文
from django.db import models
# Create your models here.
# 书籍信息表
class BookInfo(models.Model):
name = models.CharField(max_length=10)
def __str__(self):
return self.name
class Meta:
verbose_name = '书籍信息管理'
verbose_name_plural = verbose_name
# 人物信息表
class PersonInfo(models.Model):
name = models.CharField(max_length=10)
gender = models.BooleanField()
book = models.ForeignKey(BookInfo, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Meta:
verbose_name = '人物信息管理'
verbose_name_plural = verbose_name
App显示中文
- 配置
apps.py
from django.apps import AppConfig
class BookConfig(AppConfig):
name = 'book'
verbose_name = '书籍管理'
视图函数与路由系统
定义视图函数
- 配置
views.py
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
def index(request):
return HttpResponse('OK!')
配置路由系统
- 创建子路由:在
book
文件夹下建立urls.py
文件
from django.urls import path
from . import views
urlpatterns = [
path('index/', views.index),
]
- 配置总路由
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('book.urls'))
]
模板渲染
配置模板路径
- 在项目根路径下建立
templates
文件夹 - 配置
settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'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',
],
},
},
]
- 在
templates
文件夹下建立book
文件夹
建立视图
def index_2(request):
context = {
'name': '从心',
'age': '22'
}
return render(request, template_name='book/index_2.html', context=c ontext)
建立模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index_2</title>
</head>
<body>
<div>
书籍列表
<ul>
<li>西游记</li>
<li>三国演义</li>
</ul>
</div>
<div>
个人信息
<div>{{ name }}</div>
<div>{{ age }}</div>
</div>
</body>
</html>
配置文件与静态文件
BASE_DIR
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG
DEBUG = True
- 默认工作在
DEBUG
模式下 - 修改源代码程序会自动重启
-
Django
程序出现异常时会向前端显示详细的错误追踪信息
DEBUG = False
ALLOWED_HOSTS = ['*']
-
ALLOWED_HOSTS
为指定的IP
访问白名单
静态文件
- 在项目根目录下建立
static
文件夹 -
STATIC_URL
是静态文件访问路由 -
STATICFILES_DIRS
是静态文件存放路径
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
- 通过
http://127.0.0.1:8000/static/1.jpg
访问静态文件
数据库配置
建立数据库book_manager
- 字符集:
utf8mb4
- 排序规则:
utf8mb4_bin
配置settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': 'localhost',
'PORT': 3306,
'USER': 'root',
'PASSWORD': 'root',
'NAME': 'book_manager',
}
}
安装MySQL驱动
- 配置
__init__.py
import pymysql
pymysql.install_as_MySQLdb()
- 测试运行,修改最后一个链接
if query is not None:
query = query.encode(errors='replace')
数据插入
insert into book_info (name, pub_date, read_count, comment_count, is_delete) values
('射雕英雄传', '1980-5-1', 12, 34, 0),
('天龙八部', '1986-7-24', 36, 40, 0),
('笑傲江湖', '1995-12-24', 20, 80, 0),
('雪山飞狐', '1987-11-11', 58, 24, 0);
insert into person_info (name, gender, description, book_id, is_delete) values
('郭靖', 0, '降龙十八掌', 1, 0),
('黄蓉', 1, '打狗棍法', 1, 0),
('黄药师', 0, '弹指神功', 1, 0),
('欧阳锋', 0, '蛤蟆功', 1, 0),
('梅超风', 1, '九阴白骨爪', 1, 0),
('乔峰', 0, '降龙十八掌', 2, 0),
('段誉', 0, '六脉神剑', 2, 0),
('虚竹', 0, '天山六阳掌', 2, 0),
('王语嫣', 1, '神仙姐姐', 2, 0),
('令狐冲', 0, '独孤九剑', 3, 0),
('任盈盈', 1, '弹琴', 3, 0),
('岳不群', 0, '华山剑法', 3, 0),
('东方不败', 1, '葵花宝典', 3, 0),
('胡斐', 0, '胡家刀法', 4, 0),
('苗若兰', 1, '黄衣', 4, 0),
('程灵素', 1, '医术', 4, 0),
('袁紫衣', 1, '六合拳', 4, 0);
数据增加
save()方法
from book.models import BookInfo
book_info = BookInfo(
name='完美世界',
pub_date='2013-8-16'
)
book_info.save()
objects.create()方法
from book.models import BookInfo
BookInfo.objects.create(
name='斗破苍穹',
pub_date='2014-5-4'
)
数据修改
save()方法
from book.models import BookInfo
book_info = BookInfo.objects.get(id=5)
book_info.name = '斗罗大陆'
book_info.save()
objects.filter().update()方法
from book.models import BookInfo
BookInfo.objects.filter(id=6).update(name='炼气十万年')
数据删除
delete()方法
from book.models import BookInfo
book_info = BookInfo.objects.get(id=6)
book_info.delete()
objects.filter().delete()方法
from book.models import BookInfo
BookInfo.objects.filter(id=5).delete()
数据库查询
基础查询
objects.all()方法
from book.models import BookInfo
BookInfo.objects.all()
objects.count()方法
from book.models import BookInfo
BookInfo.objects.all()
objects.exclude()方法
from book.models import BookInfo
BookInfo.objects.exclude(id=1)
objects.filter()方法
from book.models import BookInfo
BookInfo.objects.filter(id=1)[0]
过滤查询
exact
from book.models import BookInfo
BookInfo.objects.get(id__exact=1)
contains
from book.models import BookInfo
BookInfo.objects.filter(name__contains='湖')
endswith
from book.models import BookInfo
BookInfo.objects.filter(name__endswith='部')
isnull
from book.models import BookInfo
BookInfo.objects.filter(name__isnull=True)
in
from book.models import BookInfo
BookInfo.objects.filter(id__in=[1, 3, 5])
gt
from book.models import BookInfo
BookInfo.objects.filter(id__gt=3)
year
from book.models import BookInfo
BookInfo.objects.filter(pub_date__year=1980)
gte
from book.models import BookInfo
BookInfo.objects.filter(pub_date__gte='1990-1-1')
F对象
from book.models import BookInfo
from django.db.models import F
BookInfo.objects.filter(read_count__gt=F('comment_count') * 2)
Q对象
逻辑与
objects.filter()方法
from book.models import BookInfo
BookInfo.objects.filter(read_count__gt=20, id__lt=3)
# BookInfo.objects.filter(read_count__gt=20).filter(id__lt=3)
Q对象
from book.models import BookInfo
from django.db.models import Q
BookInfo.objects.filter(Q(read_count__gt=20) & Q(id__lt=3))
逻辑或
from book.models import BookInfo
from django.db.models import Q
BookInfo.objects.filter(Q(read_count__gt=20) | Q(id__lt=3))
逻辑非
from book.models import BookInfo
from django.db.models import Q
BookInfo.objects.filter(~Q(id=1))
聚合函数
from book.models import BookInfo
from django.db.models import Sum, Max, Min, Avg, Count
BookInfo.objects.aggregate(Sum('read_count'))
排序函数
正序
from book.models import BookInfo
BookInfo.objects.all().order_by('read_count')
倒序
from book.models import BookInfo
BookInfo.objects.all().order_by('-read_count')
关联查询
访问
一对多的访问
from book.models import BookInfo
book = BookInfo.objects.get(id=1)
book.personinfo_set.all()
多对一的访问
from book.models import PersonInfo
person = PersonInfo.objects.get(id=1)
person.book
# person.book_id
person.book.id
过滤查询
多对一的查询
from book.models import BookInfo
book = BookInfo.objects.filter(personinfo__name='郭靖')
book
book = BookInfo.objects.filter(personinfo__description__contains='八')
book
一对多的查询
from book.models import PersonInfo
people = PersonInfo.objects.filter(book__name='天龙八部')
people
people = PersonInfo.objects.filter(book__read_count__gt=20)
people
切片
from book.models import BookInfo
BookInfo.objects.all()[0:2]
分页
from book.models import BookInfo
from django.core.paginator import Paginator
books = BookInfo.objects.all()
paginator = Paginator(books, 2)
page_1_books = list(paginator.page(1))
page_1_books
paginator.num_pages
惰性执行
- 如果用变量接收查询语句的返回结果,那么查询语句不会立即执行,而是等到调用该变量时执行
from book.models import BookInfo
books = BookInfo.objects.all()
books
缓存
- 变量的值存放在系统内存中,如果通过变量进行查询,那么不会对数据库进行查询,而是从内存中查询
from book.models import BookInfo
books = BookInfo.objects.all()
[book.id for book in books]
[book.id for book in books]
HttpRequest
路由参数
配置views.py
def url_data(request, cat_id, sku_id):
print(cat_id, sku_id)
return HttpResponse('OK!')
配置urls.py
path('<cat_id>/<sku_id>/', views.url_data)
查询字符串
配置views.py
def query_str_data(request):
print(request.GET)
a = request.GET.get('a')
b = request.GET.get('b')
print(a, b)
a_list = request.GET.getlist('a')
print(a_list)
return HttpResponse('OK!')
url
http://localhost:8000/query_str_data/?a=1&b=2&a=3
表单数据
配置views.py
def form_data(request):
print(request.POST)
username = request.POST.get('username')
password = request.POST.get('password')
print(username, password)
return HttpResponse('OK!')
关闭CSRF
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
JSON数据
配置views.py
def json_data(request):
json_data = request.body
dict_data = json.loads(json_data)
print(dict_data['username'], dict_data['age'])
return HttpResponse('OK!')
请求头数据
配置views.py
def headers_data(request):
print(request.META)
print(request.META['CONTENT_TYPE'])
print(request.method)
print(request.path)
print(request.user)
return HttpResponse('OK!')
转换器
配置converters.py
from django.urls.converters import register_converter
class TelConverter:
regex = '1[3-9]\d{9}'
def to_python(self, value):
return int(value)
def to_url(self, value):
return str(value)
register_converter(TelConverter, 'tel')
配置views.py
import converters
def tel_data(request, tel_data):
print(tel_data)
return HttpResponse('OK!')
配置urls.py
path('<tel:tel_data>/',views.tel_data)
HttpResponse
配置views.py
def http_response(request):
response = HttpResponse(content='OK!', content_type='text/plain', status=200)
response['key'] = 'value'
return response
JsonResponse
配置views.py
def json_response(request):
books_info = [
{
'id': 1,
'name': '射雕英雄传',
'pub_date': '1980-5-1'
},
{
'id': 2,
'name': '天龙八部',
'pub_date': '1986-7-24'
}
]
return JsonResponse(data=books_info, safe=False)
Redirect
配置views.py
from django.shortcuts import redirect
def redirect_url(request):
return redirect('https://www.baidu.com')
Cookie
设置Cookie
配置views.py
def set_cookie(request):
username = request.GET.get('username')
password = request.GET.get('password')
print(username, password)
response = HttpResponse('OK!')
response.set_cookie('username', username)
response.set_cookie('password', password)
return response
获取Cookie
配置views.py
def get_cookie(request):
print(request.COOKIES)
username = request.COOKIES.get('username')
password = request.COOKIES.get('password')
return HttpResponse(f'username: {username}, password: {password}')
Session
设置Session
配置views.py
def set_session(request):
username = request.GET.get('username')
user_id = 1
request.session['username'] = username
request.session['user_id'] = user_id
del request.session['user_id']
# request.session.clear()
# request.session.flush()
request.session.set_expiry(60)
return HttpResponse('OK!')
获取Session
配置views.py
def get_session(request):
username = request.session.get('username')
user_id = request.session.get('user_id')
return HttpResponse(f'username: {username}, user_id: {user_id}')
保存Session到Redis
配置settings.py
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379/1',
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
}
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'default'
类视图
类视图定义
配置views.py
from django.views import View
class LoginView(View):
def get(self, request):
return HttpResponse(f'当前请求为: {request.method}')
def post(self, request):
return HttpResponse(f'当前请求为: {request.method}')
配置urls.py
path('login/', views.LoginView.as_view())
多继承
配置views.py
from django.contrib.auth.mixins import LoginRequiredMixin
class OrderLoginView(LoginRequiredMixin, View):
def get(self, request):
return HttpResponse('个人中心页面')
def post(self, request):
return HttpResponse('个人中心页面')
中间件
中间件定义
配置middleware.py
from django.utils.deprecation import MiddlewareMixin
class TestMiddleware(MiddlewareMixin):
def process_request(self, request):
print('每次请求前, 进行调用')
username = request.COOKIES.get('username')
if username is None:
print('用户信息不存在')
else:
print('用户信息存在')
def process_response(self, request, response):
print('每次响应前, 进行调用')
return response
配置settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'book.middlewares.TestMiddleware'
]
到了这里,关于【Django】学习笔记的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!