Django学習ノート2
メールでpostを共有
djangoフォームの作成
ビューでのフォームの処理
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アプリケーションのインストール
pip install django-taggit
編集するpyファイル追加INSTALLED_APPS
'taggit',
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 {}
{}\'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アプリケーションのインストール
pip install django-taggit
編集するpyファイル追加INSTALLED_APPS
'taggit',