Django学习(五)

欢迎关注我的公众号:zx94_11

通过电子邮件共享帖子

创建表单

blog/forms.py

from django import formsclass EmailPostForm(forms.Form):    name = forms.CharField(max_length=25)    email = forms.EmailField()    to = forms.EmailField()    comments = forms.CharField(required=False, widget=forms.Textarea)

配置邮件服务器

mysite/settings.py

# Django将邮件输出至Shell中,用于缺少SMTP服务器的应用程序测试# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'# 正常的EMAIL配置EMAIL_HOST = 'smtp.163.com'  # SMTP服务器主机EMAIL_HOST_USER = '你的163邮箱'  # SMTP服务器用户名EMAIL_HOST_PASSWORD = '你163邮箱对应的密码'  # SMTP服务器密码EMAIL_PORT = 25  # SMTP端口EMAIL_USE_TLS = False  # 是否采用TLS安全连接# 在python manage.py shell进行测试# from django.core.mail import send_mail## send_mail('Django mail',  # 主题#           'This e-mail was sent with Django.',  # 消息#           '[email protected]',  # 发送者#           ['[email protected]'],  # 接收者列表#           fail_silently=False)  # 如果邮件没有被正确的发送,抛出一个异常。#                                            # 如果正常发送 输出结果为1

配置视图

blog/views.py

from .forms import EmailPostFormfrom django.core.mail import send_maildef 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)  # POST请求会生成一个表单实例        if form.is_valid():            cd = form.cleaned_data            post_url = request.build_absolute_uri(post.get_absolute_url())            subject = f'{cd["name"]} ({cd["email"]}) recommends you reding "{post.title}"'            message = f'Read "{post.title}" at {post_url}\n\n{cd["name"]} comments:{cd["comments"]}'            send_mail(subject, message, EMAIL_HOST_USER, [cd['to']])            sent = True    else:        form = EmailPostForm()  # GET请求会给出一个空表单    return render(request,                  'blog/post/share.html',                  {'post': post, 'form': form, 'sent': sent})

配置路由

blog/urls.py

path('/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 %}        

E-mail successfully sent

"{{ post.title }}" was successfully sent to {{ form.cleaned_data.to }}

{% else %}

Share "{{ post.title }}" by e-mail

{{ form.as_p }} {% csrf_token %}
{% endif %}{% endblock %}

{% csrf_token %}包含了自动生成的令牌,避免跨站点请求伪造(CSRF)

blog/templates/blog/post/detail.html{% endblock %}前面增加发送链接

Share this post

帖子详情

帖子详情

发送测试

发送测试

结果查看

页面展示结果

页面展示结果

实际结果1

实际结果1

实际结果2

实际结果2

你可能感兴趣的:(Django学习(五))