<玩转Django2.0>读书笔记:邮件和分页

时间:2022-06-01 19:13:33

1. 发送邮件

# settings.py设置
# 邮箱设置
EMAIL_USE_SSL = True
# 邮件服务器
EMAIL_HOST = 'smtp.qq.com'
# 邮件服务端口
EMAIL_PORT = 465
# 发送邮件账号
EMAIL_HOST_USER = "1223936862@qq.com"
# SMTP服务密码
EMAIL_HOST_PASSWORD = "oxwxxxxxgbrvjejc"
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
# views.py代码
from django.conf import settings
from django.core.mail import send_mail,send_mass_mail,EmailMultiAlternatives
def email_views(request):# 获取 settings.py 的配置信息
from_email = settings.DEFAULT_FROM_EMAIL # # send_mail每次发邮件都会建立一个新的连接,如果发送多封邮件,就需要建立多个连接
# send_mail("汪小鹏","来自Django的Email",from_email,['13387234406@qq.com']) # # send_mass_mail发送多封邮件
# message1 = ("汪小鹏","来自Django的Email",from_email,['13387234406@qq.com'])
# message2 = ("汪小鹏","来自Django的Email",from_email,['wangxp1994@outlook.com'])
# send_mass_mail((message1,message2),fail_silently=False) # EmailMultiAlternatives发送邮件
content = '<p>这是一封<strong>重要的</strong>邮件</p>'
msg = EmailMultiAlternatives('汪小鹏',content,from_email,['13387234406@qq.com'])
# 将正文设置成HTML格式
msg.content_subtype = "html"
# 对正文内容进行补充和添加
msg.attach_alternative('<strong>邮件来自Django</strong>','text/html')
# 添加附件
msg.attach_file('test.txt')
msg.send() return HttpResponse("发送成功")

2. 分页功能

# urls.py
...
path('page/<page>',product_views),
...
# views.py
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
def product_views(request,page):
# 获取数据表全部数据
Product_list = Product.objects.all()
# 设置每一页数据量为3
paginator = Paginator(Product_list, 3) try:
# 获取某一页的数据对象
pageInfo = paginator.page(page)
except PageNotAnInteger:
# 如果page的数据类型不是整型,就返回第一页
pageInfo = paginator.page(1)
except EmptyPage:
# 若用户访问的页数大于实际页数,则返回最后一页
pageInfo = paginator.page(paginator.num_pages) print("="*20) # 输出分页的全部数据
print(paginator.object_list)
# 获取当前被分页的数据总量
print(paginator.count)
# 获取分页的总页数
print(paginator.num_pages)
# 将页数转换成range循环对象
print(paginator.page_range)
# 判断当前页是否存在上一页
print("上一页",pageInfo.has_previous())
# 如果当前页数存在上一页,输出上一页页数,否则抛出Empty异常
print("上一页码",pageInfo.previous_page_number())
# 判断当前页是否存在上一页
print("下一页",pageInfo.has_next())
# 如果当前页数存在下一页,输出下一页页数,否则抛出Empty异常
print("下一页码",pageInfo.next_page_number())
# 输出当前页的数据信息
print("当前页",pageInfo.object_list)
# 输出当前页的第一条数据在整个数据表的位置,从1开始计算
print(pageInfo.start_index())
# 输出当前页的最后一条数据在整个数据表的位置,从1开始计算
print(pageInfo.end_index())
return render(request,"page.html",locals())