第二章内容:
利用django发送邮件
创建表单并在视图中加以处理
从模型中创建表单
整合第三方应用程序
构建复杂的QuerySet
2.1通过电子邮件共享帖子
针对帖子的邮件发送功能,需要执行以下操作:
- 创建用户表单,并填写名字,邮件,收件人,可选的备注功能。
- 在views.py文件中创建视图,并处理数据以及发送邮件.
- 在blog应用程序的urls.py文件中,针对新视图添加url路径。
- ’ 创建模板并显示表单。
django自带基类:Form,ModelForm
在blog目录下创建forms.py
from django import forms
class EmailPostForm(forms.Form):
name = forms.CharField(max_length=25)
email = forms.EmailField()
to = forms.EmailField()
comments = forms.CharField(required=False, widget=forms.Textarea)
setting中配置邮件参数:
# 发送邮件配置
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# smpt服务地址
EMAIL_HOST = 'smtp.qq.com'
EMAIL_PORT = 25 # 端口默认都是25不需要修改
# 发送邮件的邮箱,需要配置开通SMTP
EMAIL_HOST_USER = 'xxx@qq.com'
# 在邮箱中设置的客户端授权密码
EMAIL_HOST_PASSWORD = 'xxx'
# 收件人看到的发件人
EMAIL_FROM = '带签名的<xxx@qq.com>'
views.py中处理表单:
def post_share(request, post_id):
post = get_object_or_404(Post, id=post_id, status='published')
sent = False
if request.method == 'POST':
form = EmailPostForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
post_url = request.build_absolute_uri(post.get_absolute_url())
subject = '{} ({}) recommends you reading"{}"'.format(cd['name'], cd['email'], post.title)
message = 'Read "{}" at {}\n\n{}\'s comments:{}'.format(post.title, post_url, cd['name'], cd['comments'])
send_mail(subject, message, 'xxx@qq.com', [cd['to']])
sent = True
else:
form = EmailPostForm()
return render(request, 'blog/post/share.html', {
"post": post, "form": form, 'sent': sent})
配置blog/urls.py:
path('<int:post_id>/share/', views.post_share, name='post_share'),
在blog/templates/blog/post 创建新文件,share.html,添加下面代码:
{
% extends "blog/base.html" %}
{
% block title %}share a post {
% endblock %}
{
% block content %}
{
% if sent %}
<h1>E-mail successfully sent</h1>
<p>
"{
{ post.title }}" was successfully sent to {
{
form.cleaned_data.to }}.
</p>
{
% else %}
<h1>Share"{
{ post.title }}"by e-mail</h1>
<form action="." method=