创建表单
在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)
上述代码通过Form基类创建了一个表单
处理视图中的表单
对新创建的表单加以处理,但提交成功后,将发送一封电子邮件
def post_share(request, post_id):
post = get_object_or_404(Post, id=post_id, status='published')
if request.method == 'POST':
form = EmailPostForm(request.POST)
if form.is_valid()():
cd = form.cleaned_data
else:
form = EmailPostForm()
return render(request,'blog/post/share.html',{'post': post, 'form': form})
发送邮件
settting.py中添加
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'your_account@gmail.com'
EMAIL_HOST_PASSWORD = 'your_password'
EMAIL_POST = 587
EMAIL_USE_TLS = True
然后运行shell,发送邮件
from django.core.mail import send_mail
send_mail('Django mail', 'This e-mail was send with Django.','your_account@gmail.com',['your_account@gmail.com'], fail_silently=False)
输出结果为1则发送正常
向post_share中添加功能
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 commends:{}'.format(post.title, post_url, cd['name'], cd['commends'])
send_mail(subject, message, 'admin@myblog.com', cd['to'])
sent = True
else:
form = EmailPostForm()
return render(request,'blog/post/share.html',{'post': post, 'form': form, 'sent': sent})
显示模板视图
1.设置模板,添加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="post">
{{ form.as_p }}
{% csrf_token %}
<input type="submit" value="Send e-mail">
</form>
{% endif %}
{% endblock %}
2.编辑detail.html
<p>
<a href="{% url "blog:post_share" post.id %}">
Share this post
</a>
</p>