目录
Day04练习
day04文件夹
# __init__.py
import pymysql
pymysql.install_as_MySQLdb()
# settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'index',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'webdb',
'USER': 'root',
'PASSWORD': '123456',
'HOST': 'localhost',
'PORT': '3306',
}
}
# urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^',include('index.urls')),
]
index
# models.py
from django.db import models
# Create your models here.
# 创建 Publisher 实体类
# 表示 出版社 的信息,属性如下:
# 1.name : 出版社的名称(varchar,string)
# 2.address : 出版社的地址
# 3.city : 出版社所在城市
# 4.country : 出版社所在国家
# 5.website : 出版社的网址
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=20)
country = models.CharField(max_length=20)
website = models.URLField()
class Author(models.Model):
name = models.CharField(max_length=50)
age = models.IntegerField()
email = models.EmailField(null=True)
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length=50)
publicate_date = models.DateField()
# urls.py
from django.conf.urls import url
from .views import *
urlpatterns = [
# 访问路径是 /01_add , 交给 add_views 处理
url(r'^01_add/$',add_views),
# 访问路径是 /02_query, 交给 query_views 处理
url(r'^02_query/$',query_views),
]
# views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse
from django.shortcuts import render
from .models import *
# Create your views here.
# /01_add 所对应的视图
def add_views(request):
# 向 Author 实体中增加一条数据
# ret = Author.objects.create(name='老舍',age=85,email='[email protected]')
# return HttpResponse(ret)
# 使用方式2 向Author表中增加数据
# author = Author(name='巴金',age=75,email='[email protected]')
# ret = author.save()
# return HttpResponse(ret)
# 使用方式3 向Author表中增加数据
dic = {
'name': '冰心',
'age': '96',
'email': '[email protected]'
}
author = Author(**dic)
author.save()
return HttpResponse('Add OK')
def query_views(request):
# 1. 查询 Author 实体(表)中所有的数据
# authors = Author.objects.all()
# # 循环便利 authors 中的每条记录
# for au in authors:
# print(au.name,au.age,au.email)
# 2. 查询 Author 实体中name和age两个列的信息
# authors = Author.objects.values('name','age')
# # print(authors)
# for au in authors:
# print(au['name'],au['age'])
# 3.查询 Author 实体中name和age两个列的信息
# authors = Author.objects.values_list('name','age')
# print(authors)
# 4.Author表中的数据按照年龄降序排序
authors = Author.objects.order_by('-age')
print(authors)
return HttpResponse('Query OK')
Day05练习
Day04文件夹
# settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'index',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'webdb',
'USER': 'root',
'PASSWORD': '123456',
'HOST': 'localhost',
'PORT': '3306',
}
}
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^',include('index.urls')),
]
index
# admin.py
from django.contrib import admin
from .models import *
# 定义 Author 的高级管理类
class AuthorAdmin(admin.ModelAdmin):
#1.指定在列表页中显示的字段们
list_display = ('name','age','email')
#2.指定能够链接到详情页的链接们
list_display_links = ('name','email')
#3.指定在列表页中就允许被修改的字段们
list_editable = ('age',)
#4.指定允许被搜索的字段们
search_fields = ('name','email')
#5.指定右侧过滤器中允许筛选的字段们
list_filter = ('name','email')
#7.指定在详情页中显示的字段们以及顺序
# fields = ('age','name')
#8.指定在详情页中的字段分组
fieldsets = (
#分组1
(
"基本选项",{
"fields":('name','age'),
}
),
#分组2
(
"高级选项",{
"fields":('email','isActive'),
"classes":("collapse",)
}
)
)
class BookAdmin(admin.ModelAdmin):
#6.增加时间选择器
date_hierarchy = "publicate_date"
# Register your models here.
admin.site.register(Author,AuthorAdmin)
admin.site.register(Book,BookAdmin)
# models.py
from django.db import models
# Create your models here.
# 创建 Publisher 实体类
# 表示 出版社 的信息,属性如下:
# 1.name : 出版社的名称(varchar,string)
# 2.address : 出版社的地址
# 3.city : 出版社所在城市
# 4.country : 出版社所在国家
# 5.website : 出版社的网址
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=20)
country = models.CharField(max_length=20)
website = models.URLField()
class Author(models.Model):
name = models.CharField(max_length=50,verbose_name='姓名')
age = models.IntegerField(verbose_name='年龄')
email = models.EmailField(null=True,verbose_name='邮箱')
isActive = models.BooleanField(default=True,verbose_name='激活')
def __str__(self):
return self.name
class Meta:
db_table = "author"
verbose_name = "作者"
verbose_name_plural = verbose_name
ordering = ["-age","-name"]
class Book(models.Model):
title = models.CharField(max_length=50)
publicate_date = models.DateField()
def __str__(self):
return self.title
# urls.py
from django.conf.urls import url
from .views import *
urlpatterns = [
# 访问路径是 /01_add , 交给 add_views 处理
url(r'^01_add/$',add_views),
# 访问路径是 /02_query, 交给 query_views 处理
url(r'^02_query/$',query_views),
# 访问路径是 /03_queryall,交给queryall_views处理
url(r'^03_queryall/$',queryall_views,name='all'),
# 访问路径是 /04_get , 交给get_views去处理
url(r'^04_get/$',get_views),
# 访问路径是 /05_getau/(\d+) 交给getau_views去处理
url(r'^05_getau/(\d+)/$',getau_views,name='getau'),
# 访问路径是 /06_filter/ 交给 filter_views
url(r'^06_filter/$',filter_views),
# 访问路径是 /07_email/ 交给 email_views
url(r'^07_email/$',email_views),
# 访问路径是 /08_delete/(\d+) 交给 delete_views
url(r'^08_delete/(\d+)/$',delete_views,name='del'),
# 访问路径是 /09_updateage/ 交给 updateage_views
url(r'^09_updateage/$',updateAge_views),
]
# views.py
from django.db.models import F, Q
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from django.urls import reverse
from .models import *
# Create your views here.
# /01_add 所对应的视图
def add_views(request):
# 向 Author 实体中增加一条数据
# ret = Author.objects.create(name='老舍',age=85,email='[email protected]')
# return HttpResponse(ret)
# 使用方式2 向Author表中增加数据
# author = Author(name='巴金',age=75,email='[email protected]')
# ret = author.save()
# return HttpResponse(ret)
# 使用方式3 向Author表中增加数据
dic = {
'name':'冰心',
'age':'96',
'email':'[email protected]'
}
author = Author(**dic)
author.save()
return HttpResponse('Add OK')
def query_views(request):
# 1. 查询 Author 实体(表)中所有的数据
# authors = Author.objects.all()
# # 循环便利 authors 中的每条记录
# for au in authors:
# print(au.name,au.age,au.email)
# 2. 查询 Author 实体中name和age两个列的信息
# authors = Author.objects.values('name','age')
# # print(authors)
# for au in authors:
# print(au['name'],au['age'])
# 3.查询 Author 实体中name和age两个列的信息
# authors = Author.objects.values_list('name','age')
# print(authors)
# 4.Author表中的数据按照年龄降序排序
authors = Author.objects.order_by('-age')
print(authors)
return HttpResponse('Query OK')
def queryall_views(request):
# 查询所有数据按年龄降序排序
# authors = Author.objects.order_by('-age')
# 查询所有isActive为True的数据,并按年龄降序排序
authors = Author.objects.filter(isActive=True).order_by("-age")
return render(request,'01_all.html',locals())
def get_views(request):
author=Author.objects.get(name='舒庆春')
print(author)
return HttpResponse('Query OK')
def getau_views(request,id):
au = Author.objects.get(id=id)
return render(request,'02_author.html',locals())
def filter_views(request):
# auList = Author.objects.filter(id=1,name='老舍')
auList = Author.objects.filter(name='莫言')
print(auList)
return HttpResponse('Query OK')
def email_views(request):
auList=Author.objects.filter(email__contains='a')
for au in auList:
print(au.name,au.age,au.email)
return HttpResponse("Query OK")
def delete_views(request,id):
au = Author.objects.get(id=id)
au.isActive = False
au.save()
# 使用转发
# return queryall_views(request)
# 使用重定向
# return HttpResponseRedirect('/03_queryall/')
url = reverse('all')
print(url)
return redirect(url)
def updateAge_views(request):
# Author.objects.all().update(age=F('age')+10)
# 查询id=1或年龄大于100的author的信息
auList=Author.objects.filter(Q(id=1)|Q(age__gt=100),isActive=1)
for au in auList:
print(au.name,au.age,au.email)
return redirect(reverse('all'))
templates
# 01_all.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1">
<tr>
<td>姓名</td>
<td>年龄</td>
<td>邮箱</td>
<td>操作</td>
</tr>
{% for au in authors %}
<tr>
<td>{{ au.name }}</td>
<td>{{ au.age }}</td>
<td>{{ au.email }}</td>
<td>
<a href="{% url 'del' au.id %}">删除</a>
<!-- <a href="/05_getau/{{ au.id }}/">修改</a> -->
<a href="{% url 'getau' au.id %}">修改</a>
</td>
</tr>
{% endfor %}
</table>
</body>
</html>
# 02_author.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/" method="post">
<p>
姓名:
<input type="text" name="uname" value="{{ au.name }}">
</p>
<p>
年龄:
<input type="text" name="uage" value="{{ au.age }}">
</p>
<p>
邮箱:
<input type="email" name="uemail" value="{{ au.email }}">
</p>
<p>
<input type="submit" value="修改">
</p>
</form>
</body>
</html>
Day06练习
index
# models.py
from django.db import models
# Create your models here.
# 创建 Publisher 实体类
# 表示 出版社 的信息,属性如下:
# 1.name : 出版社的名称(varchar,string)
# 2.address : 出版社的地址
# 3.city : 出版社所在城市
# 4.country : 出版社所在国家
# 5.website : 出版社的网址
class Publisher(models.Model):
name = models.CharField(max_length=30,verbose_name='名称')
address = models.CharField(max_length=50,verbose_name='地址')
city = models.CharField(max_length=20,verbose_name='城市')
country = models.CharField(max_length=20,verbose_name='国家')
website = models.URLField(verbose_name='网址')
def __str__(self):
return self.name
class Meta:
db_table='publisher'
verbose_name='出版社'
verbose_name_plural=verbose_name
class Author(models.Model):
name = models.CharField(max_length=50,verbose_name='姓名')
age = models.IntegerField(verbose_name='年龄')
email = models.EmailField(null=True,verbose_name='邮箱')
isActive = models.BooleanField(default=True,verbose_name='激活')
# 增加对 Publisher 的多对多的引用
publisher = models.ManyToManyField(Publisher,verbose_name='出版社')
def __str__(self):
return self.name
class Meta:
db_table = "author"
verbose_name = "作者"
verbose_name_plural = verbose_name
ordering = ["-age","-name"]
class Book(models.Model):
title = models.CharField(max_length=50)
publicate_date = models.DateField()
#增加对Publisher(1)的引用
publisher = models.ForeignKey(Publisher,null=True)
#增加对Author的引用(多对多)
author = models.ManyToManyField(Author)
def __str__(self):
return self.title
class Meta:
db_table = "book"
# 编写Wife的实体类,与Author做:1:1的引用
class Wife(models.Model):
name = models.CharField(max_length=30,verbose_name='姓名')
age = models.IntegerField(verbose_name='年龄')
#指定一对一的关联关系,引用自Author实体
author = models.OneToOneField(Author)
def __str__(self):
return self.name
# views.py
# 访问路径 /10_oto/
def oto_views(request):
# 先获取id为1的wife的信息
wife = Wife.objects.get(id=1)
# 再获取对应的author
author = wife.author
# 先获取id为2的author的信息
a = Author.objects.get(id=2)
# 再获取author对应的wife的信息
w = a.wife
return render(request, '03_oto.html', locals())
# 访问路径 /11_otm/
def otm_views(request):
# 先查询id为1的book的信息
book = Book.objects.get(id=1)
# 再查询book的关联的publisher
publisher = book.publisher
# 先查询id为2的Publisher
pub = Publisher.objects.get(id=2)
# 再查询关联的所有的书籍
bookList = pub.book_set.all()
return render(request, '04_otm.html', locals())
# /12_mtm/
def mtm_views(request):
# 查询id为2的book的信息
book = Book.objects.get(id=2)
# 查询book对应的所有的作者的信息
authors = book.author.all()
# 查询id为2的Author的信息
author = Author.objects.get(id=2)
# 查询author所对应的所有的书籍的信息
books = author.book_set.all()
return render(request, '05_mtm.html', locals())
# /13_exer/
def exer_views(request):
# 正向查询:通过 Author 查询 Publisher
author = Author.objects.get(name='老舍')
pubList = author.publisher.all()
print('正向查询:')
print(author.name)
for pub in pubList:
print(pub.name, pub.website)
# 反向查询:通过 Publisher 查询 Author
pub = Publisher.objects.get(name='北京大学出版社')
auList = pub.author_set.all()
print('反向查询:')
print(pub.name)
for au in auList:
print(au.name, au.email)
return HttpResponse('Query OK')
templates
# 03_oto.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>正向查询(Wife -> Author)</h1>
<h2>Wife 信息:</h2>
<h3>姓名:{{ wife.name }}</h3>
<h3>年龄:{{ wife.age }}</h3>
<h2>Author 信息:</h2>
<h3>姓名:{{ author.name }}</h3>
<h3>姓名:{{ wife.author.name }}</h3>
<h3>年龄:{{ author.age }}</h3>
<h3>邮箱:{{ author.email }}</h3>
<h1>反向查询(Author -> Wife)</h1>
<h2>Author 信息:</h2>
<h3>姓名:{{ a.name }}</h3>
<h3>年龄:{{ a.age }}</h3>
<h3>邮箱:{{ a.email }}</h3>
<h2>Wife 信息:</h2>
<h3>姓名:{{ w.name }}</h3>
<h3>年龄:{{ w.age }}</h3>
</body>
</html>
# 04_otm.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>正向查询 (Book -> Publisher)</h1>
<h2>图书信息:</h2>
<h3>书名:{{ book.title }}</h3>
<h3>出版时间:{{ book.publicate_date }}</h3>
<h2>出版社信息:</h2>
<h3>出版社:{{ publisher.name }}</h3>
<h3>网址:
<a href="{{ publisher.website }}">
{{ publisher.website }}
</a>
</h3>
<h1>反向查询 (Publisher -> Book)</h1>
<h2>出版社信息:</h2>
<h3>名称:{{ pub.name }}</h3>
<h3>地址:{{ pub.address }}</h3>
<h2>书籍信息:</h2>
{% for book in bookList %}
<h3>书名:{{ book.title }}</h3>
<h3>出版时间:{{ book.publicate_date }}</h3>
{% endfor %}
</body>
</html>
# 05_mtm.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>正向查询(Book -> Author们)</h1>
<h2>书籍信息:</h2>
<h3>书名:{{ book.title }}</h3>
<h3>出版时间:{{ book.publicate_date }}</h3>
<h2>作者们:</h2>
{% for author in authors %}
<h3>姓名:{{ author.name }}</h3>
<h3>邮箱:{{ author.email }}</h3>
{% endfor %}
<h1>反向查询(Author -> Book们)</h1>
<h2>作者信息:</h2>
<h3>姓名:{{ author.name }}</h3>
<h3>邮箱:{{ author.email }}</h3>
<h2>书籍信息:</h2>
{% for book in books %}
<h3>书名:{{ book.title }}</h3>
<h3>出版时间:{{ book.publicate_date }}</h3>
{% endfor %}
</body>
</html>
Day07练习
day04文件夹
# __init__.py
import pymysql
pymysql.install_as_MySQLdb()
# settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'day07',
'USER':'root',
'PASSWORD':'123456',
'HOST':'localhost',
'PORT':'3306',
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^',include('index.urls')),
]
index
# admin.py
from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(Users)
# forms.py
# -*- coding: utf-8 -*-
from django import forms
# TOPIC'S initial display and value
TOPIC_CHOICE = (
('1', '好评'),
('2', '中评'),
('3', '差评'),
)
# 表示评论内容的表单控件们
# 评论标题 - 文本框
# Email - Input type='Email'
# 评论区 Message - Textarea
# 评价 Topic - Select
# 是否保存isSave - Input type='checkbox'
class RemarkForm(forms.Form):
# Subject - Input type="text"
# 创建标题,label : 控件前显示的文本
subject = forms.CharField(label='Title')
# Email - Input type="email"
email = forms.EmailField(label='Email')
# Message - Textarea
# widget=forms.Textarea , set the message is a <textarea></textarea>
# 创建评论内容,widget指定显示为多行文本域
message = forms.CharField(label='Message', widget=forms.Textarea)
# 下拉选择框 topic - <select></select>
#<select>
# <option value='1'>好评</option>
# <option value='2'>中评</option>
# <option value='3'>差评</option>
# </select>
# 评论级别,choices指定select中显示的数据
topic = forms.ChoiceField(label='Topic', choices=TOPIC_CHOICE)
# ISSAVED Input type='checkbox'
isSaved = forms.BooleanField(label="IsSaved")
# 创建class表示登录的表单
class LoginForm(forms.Form):
# 文本框,表示用户名
uname = forms.CharField(label='用户名称')
# 密码框,表示用户密码
upwd = forms.CharField(label='登录密码', widget=forms.PasswordInput)
# models.py
from django.db import models
# Create your models here.
class Users(models.Model):
uname = models.CharField(max_length=30)
upwd = models.CharField(max_length=30)
uage = models.IntegerField()
uemail = models.EmailField()
def __str__(self):
return self.uname
# urls.py
from django.conf.urls import url
from .views import *
urlpatterns = [
# 访问路径是 /01_request/ 的时候,交给request_views去处理
url(r'^01_request/$',request_views),
# 访问路径是 /02_meta/ 的时候,交给meta_views去处理
url(r'^02_meta/$',meta_views),
# 访问路径是 /03_form/ 的时候,交给form_views去处理
url(r'^03_form/$',form_views),
# 访问路径是 /04_get/ 的时候,交给get_views去处理
url(r'^04_get/$',get_views,name='get'),
# 访问路径是 /05_post/ 的时候,交给post_views去处理
url(r'^05_post/$',post_views,name='post'),
# 访问路径是 /06_login/ 的时候,交给login_views去处理
url(r'^06_login/$',login_views),
# 访问路径是 /07_remark/ 的时候,交给remark_views去处理
url(r'^07_remark/$',remark_views),
# 访问路径是 /08_userLogin/的时候,交给userLogin_views处理
url(r'^08_userLogin/$',userLogin_views),
]
# views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse
from django.shortcuts import render
from .forms import *
from .models import *
# Create your views here.
def request_views(request):
# request,类型就是 HttpRequest
# request 封装的是所有与请求相关的内容
# print(dir(request))
# 协议 (方案)
scheme = request.scheme
# 请求主体
body = request.body
# 请求资源的具体路径
path = request.path
# 请求主机的地址 / 域名
host = request.get_host()
# 请求方法
method = request.method
# get方式请求数据
get = request.GET
# post方式请求数据
post = request.POST
# cookie 中的数据
cookies = request.COOKIES
# 请求的元数据
meta = request.META
return render(request, '01_request.html', locals())
# /02_meta/
# 通过01_request 跳转
def meta_views(request):
if 'HTTP_REFERER' in request.META:
print('请求源地址为:' + request.META['HTTP_REFERER'])
# http://localhost:8000/01_request/
return HttpResponse("Request OK")
# /03_form/
def form_views(request):
return render(request, '02_form.html')
# /04_get/
def get_views(request):
print(request.GET)
# <QueryDict: {'uname': ['tarena'], 'upwd': ['zhangsanfeng']}>
uname = request.GET['uname']
upwd = request.GET['upwd']
return HttpResponse("用户名:" + uname + ",密码:" + upwd)
# /05_post/
def post_views(request):
uname = request.POST['uname']
upwd = request.POST['upwd']
return HttpResponse("用户名:" + uname + ",密码:" + upwd)
# /06_login/
def login_views(request):
if request.method == "GET":
return render(request, '03_login.html')
else:
uname = request.POST['uname']
upwd = request.POST['upwd']
return HttpResponse('uname:' + uname + ',upwd:' + upwd)
# /07_remark/
def remark_views(request):
form = RemarkForm()
return render(request, '04_remark.html', locals())
# /08_userLogin/
def userLogin_views(request):
if request.method == 'GET':
form = LoginForm()
return render(request, '05_login.html', locals())
else:
# 1.手动接收提交的数据
# uname = request.POST['uname']
# upwd = request.POST['upwd']
# 2.自动接收提交的数据
# 2.1 通过 forms.Form的构造,接收request.POST
form = LoginForm(request.POST)
# 2.2 is_valid()
if form.is_valid():
# 2.3 form.cleaned_data
cd = form.cleaned_data
print(cd)
print(request.POST)
uname = cd['uname']
upwd = cd['upwd']
uList = Users.objects.filter(uname=uname, upwd=upwd)
if uList:
return HttpResponse('登录成功')
else:
form = LoginForm()
errMsg = "用户名或密码不正确"
return render(request, '05_login.html', locals())