Django 学习笔记二

通过邮件分享post

django创建表单

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)


在视图中处理表单

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(  # 获取FQDN的url地址 有http和主机地址
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, '[email protected]',
[cd['to']])
sent = True
else:
form = EmailPostForm()
return render(request, 'blog/post/share.html', {'post': post,
'form': form,
'sent': sent})


在django中发送邮件

在setting中添加

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

EMAIL_HOST = 'smtp.163.com'

EMAIL_HOST_USER = '[email protected]'

EMAIL_HOST_PASSWORD = 'XXXXXX'

EMAIL_USE_TLS = True


在django 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)


增加tag标签

安装tag应用

pip install django-taggit

编辑settings.py文件 添加INSTALLED_APPS

'taggit',



你可能感兴趣的:(django,学习,笔记)