Django學(xué)習(xí)(五)

歡迎關(guān)注我的公眾號(hào):zx94_11

通過(guò)電子郵件共享帖子

創(chuàng)建表單

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)

配置郵件服務(wù)器

mysite/settings.py

# Django將郵件輸出至Shell中,用于缺少SMTP服務(wù)器的應(yīng)用程序測(cè)試# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'# 正常的EMAIL配置EMAIL_HOST = 'smtp.163.com'  # SMTP服務(wù)器主機(jī)EMAIL_HOST_USER = '你的163郵箱'  # SMTP服務(wù)器用戶(hù)名EMAIL_HOST_PASSWORD = '你163郵箱對(duì)應(yīng)的密碼'  # SMTP服務(wù)器密碼EMAIL_PORT = 25  # SMTP端口EMAIL_USE_TLS = False  # 是否采用TLS安全連接# 在python manage.py shell進(jìn)行測(cè)試# from django.core.mail import send_mail## send_mail('Django mail',  # 主題#           'This e-mail was sent with Django.',  # 消息#           'zx490336534@163.com',  # 發(fā)送者#           ['490336534@qq.com'],  # 接收者列表#           fail_silently=False)  # 如果郵件沒(méi)有被正確的發(fā)送,拋出一個(gè)異常。#                                            # 如果正常發(fā)送 輸出結(jié)果為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請(qǐng)求會(huì)生成一個(gè)表單實(shí)例        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請(qǐng)求會(huì)給出一個(gè)空表單    return render(request,                  'blog/post/share.html',                  {'post': post, 'form': form, 'sent': sent})

配置路由

blog/urls.py

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

{% csrf_token %}包含了自動(dòng)生成的令牌,避免跨站點(diǎn)請(qǐng)求偽造(CSRF)

blog/templates/blog/post/detail.html{% endblock %}前面增加發(fā)送鏈接

<p>    <a href="{% url 'blog:post_share' post.id %}">        Share this post    </a></p>
帖子詳情

<figcaption style="line-height: inherit; margin: 0px; padding: 0px; margin-top: 10px; text-align: center; color: rgb(153, 153, 153); font-size: 0.7em;">帖子詳情</figcaption>

發(fā)送測(cè)試

<figcaption style="line-height: inherit; margin: 0px; padding: 0px; margin-top: 10px; text-align: center; color: rgb(153, 153, 153); font-size: 0.7em;">發(fā)送測(cè)試</figcaption>

結(jié)果查看

頁(yè)面展示結(jié)果

<figcaption style="line-height: inherit; margin: 0px; padding: 0px; margin-top: 10px; text-align: center; color: rgb(153, 153, 153); font-size: 0.7em;">頁(yè)面展示結(jié)果</figcaption>

實(shí)際結(jié)果1

<figcaption style="line-height: inherit; margin: 0px; padding: 0px; margin-top: 10px; text-align: center; color: rgb(153, 153, 153); font-size: 0.7em;">實(shí)際結(jié)果1</figcaption>

實(shí)際結(jié)果2

<figcaption style="line-height: inherit; margin: 0px; padding: 0px; margin-top: 10px; text-align: center; color: rgb(153, 153, 153); font-size: 0.7em;">實(shí)際結(jié)果2</figcaption>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容