用户可通过发送邮件共享帖子。
1. 利用Django创建表单
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)
2. 处理视图中的表单
编辑blog应用程序的views.py文件,添加如下代码:
from .forms import EmailPostForm
def post_share(request,post_id):
# Retrieve post by id
post = get_object_or_404(Post,id=post_id,status='published')
if request.method == 'POST':
# Form was submitted
form = EmailPostForm(request.POST)
if form.is_valid():
# Form fields passed validation
cd = form.cleaned_data
# ... send email
else:
form = EmailPostForm()
return render(request,'blog/post/share.html',{'post':post,
'form':form})
3. 利用Django发送邮件
-
首先,设置本地SMTP服务器
在settings.py中添加下列设置
# Email
EMAIL_HOST = 'smtp.qq.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'me@zhangzhixiong.com'
EMAIL_HOST_PASSWORD = '16位字母的授权码'
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
运行python manage.py shell
命令,打开Python Shell并发送邮件,如下所示:
>>> from django.core.mail import send_mail
>>> send_mail('Django mail','This e-mail was sent with Django.','me@zhangzhixiong.com',['covfefe@qq.com'],fail_silently=False)
1
-
编辑blog应用程序views.py文件中的post_share视图,如下所示:
from django.core.mail import send_mail
def post_share(request,post_id):
# Retrieve post by id
post = get_object_or_404(Post,id=post_id,status='published')
sent = False
if request.method == 'POST':
# Form was submitted
form = EmailPostForm(request.POST)
if form.is_valid():
# Form fields passed validation
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,'me@zhangzhixiong.com',[cd['to']])
sent = True
else:
form = EmailPostForm()
return render(request,'blog/post/share.html',{'post':post,
'form':form,
'sent':sent})
4. 添加新的URL
打开blog应用程序的urls.py文件,加入post_share URL路径,如下所示:
urlpatterns = [
# ...
path('<int:post_id>/share/',views.post_share,name='post_share'),
]
5. 针对视图设置模板
-
在blog/templates/blog/post/目录中创建新文件,命名为share.html,并添加下列代码:
{% extends "blog/base.html" %}
{% block title %}Share a post{% endblock %}
{% block content %}
{% if sent %}
<h1>E-mail sent successfully.</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="post">
{{ form.as_p }}
{% csrf_token %}
<input type="submit" value="Send e-mail">
</form>
{% endif %}
{% endblock %}
-
编辑blog/post/detail.html
<p><a href="{% url "blog:post_share" post.id %}">Share this post</a></p>