赞
踩
个人主页:丷从心·
系列专栏:Django
pip install django==2.2.5
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',
]
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
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
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 = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
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
访问静态文件utf8mb4
utf8mb4_bin
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': 'localhost',
'PORT': 3306,
'USER': 'root',
'PASSWORD': 'root',
'NAME': 'book_manager',
}
}
__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);
from book.models import BookInfo
book_info = BookInfo(
name='完美世界',
pub_date='2013-8-16'
)
book_info.save()
from book.models import BookInfo
BookInfo.objects.create(
name='斗破苍穹',
pub_date='2014-5-4'
)
from book.models import BookInfo
book_info = BookInfo.objects.get(id=5)
book_info.name = '斗罗大陆'
book_info.save()
from book.models import BookInfo
BookInfo.objects.filter(id=6).update(name='炼气十万年')
from book.models import BookInfo
book_info = BookInfo.objects.get(id=6)
book_info.delete()
from book.models import BookInfo
BookInfo.objects.filter(id=5).delete()
from book.models import BookInfo
BookInfo.objects.all()
from book.models import BookInfo
BookInfo.objects.all()
from book.models import BookInfo
BookInfo.objects.exclude(id=1)
from book.models import BookInfo
BookInfo.objects.filter(id=1)[0]
from book.models import BookInfo
BookInfo.objects.get(id__exact=1)
from book.models import BookInfo
BookInfo.objects.filter(name__contains='湖')
from book.models import BookInfo
BookInfo.objects.filter(name__endswith='部')
from book.models import BookInfo
BookInfo.objects.filter(name__isnull=True)
from book.models import BookInfo
BookInfo.objects.filter(id__in=[1, 3, 5])
from book.models import BookInfo
BookInfo.objects.filter(id__gt=3)
from book.models import BookInfo
BookInfo.objects.filter(pub_date__year=1980)
from book.models import BookInfo
BookInfo.objects.filter(pub_date__gte='1990-1-1')
from book.models import BookInfo
from django.db.models import F
BookInfo.objects.filter(read_count__gt=F('comment_count') * 2)
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)
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]
def url_data(request, cat_id, sku_id):
print(cat_id, sku_id)
return HttpResponse('OK!')
path('<cat_id>/<sku_id>/', views.url_data)
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!')
http://localhost:8000/query_str_data/?a=1&b=2&a=3
def form_data(request):
print(request.POST)
username = request.POST.get('username')
password = request.POST.get('password')
print(username, password)
return HttpResponse('OK!')
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',
]
def json_data(request):
json_data = request.body
dict_data = json.loads(json_data)
print(dict_data['username'], dict_data['age'])
return HttpResponse('OK!')
def headers_data(request):
print(request.META)
print(request.META['CONTENT_TYPE'])
print(request.method)
print(request.path)
print(request.user)
return HttpResponse('OK!')
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')
import converters
def tel_data(request, tel_data):
print(tel_data)
return HttpResponse('OK!')
path('<tel:tel_data>/',views.tel_data)
def http_response(request):
response = HttpResponse(content='OK!', content_type='text/plain', status=200)
response['key'] = 'value'
return response
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)
from django.shortcuts import redirect
def redirect_url(request):
return redirect('https://www.baidu.com')
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
def get_cookie(request):
print(request.COOKIES)
username = request.COOKIES.get('username')
password = request.COOKIES.get('password')
return HttpResponse(f'username: {username}, password: {password}')
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!')
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}')
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'
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}')
path('login/', views.LoginView.as_view())
from django.contrib.auth.mixins import LoginRequiredMixin
class OrderLoginView(LoginRequiredMixin, View):
def get(self, request):
return HttpResponse('个人中心页面')
def post(self, request):
return HttpResponse('个人中心页面')
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
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'
]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。