FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Django学习记录(十四):Django by example -- Blog(十) · Issue #50 · PyxYuYu/MyBlog · GitHub

Repository navigation

Django学习记录(十四):Django by example -- Blog(十) #50

Open

Description

If the world seems cold to you, kindle fires to warm it.

0x01 Django

  • Build a Blog Application
    • Sending e-mails with Django

      • 发送邮件的话,需要一个本地的 SMTP 服务器或者 网络 SMTP 服务器
    • 网络 STMP 服务器的话,需要在 settings.py 中添加:

      • EMAIL_HOST : SMTP 服务器主机,默认 localhost
      • EMAIL_PORT : SMTP 接口,默认25
      • EMAIL_HOST_USER : 用户名
      • EMAIL_HOST_PASSWORD : 密码
      • EMAIL_USE_TLS : 是否用 TLS 安全连接
      • EMAIL_USE_SSL : 是否用 SSL 安全连接
      • 例如,添加:
        EMAIL_HOST = 'smtp.163.com'
        EMAIL_HOST_USER = 'your_account'
        EMAIL_HOST_PASSWORD = 'your_password'
        EMAIL_PORT = 25
        EMAIL_USE_TLS = True
      
      • 调用命令行,可以测试发送功能是否成功
      • python manage.py shell
        >>> from django.core.mail import send_mail
        >>> send_mail('Django mail', 'Test!!!!', 'your_account@163.com', ['recipient@xxx.com'], fail_silently=False)
      • fail_silently 这个参数可以回显发送是否成功,成功返回 1,失败的话,返回异常
      • 将上面的代码,添加到 views.py 中
        from django.core.mail import send_mail
        from .forms import EmailPostForm
      
        def post_share(request, post_id):
            # 通过id检索post内容
            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 comments: {}'.format(post.title, post_url, cd['name'], cd['comments'])
                    send_mail(subject, message, 'your_account@163.com', [cd['to']])
                    sent = True
            else:
                form = EmailPostForm()
            return render(request, 'blog/post/share.html', {'post': post, 'form': form, 'sent': sent})
      • 上面定义了一个参数 sent ,如果发送了则为 True,否则 False,这个参数会在之后的 html 模板中出现
      • 视图完成后,还需要在 blog/urls.py 中添加一个 URL pattern
        urlpatterns = [
            # ...
            url(r'^(?P<post_id>\d+)/share/$', views.post_share, name='post_share'),
        ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions


      Back | FazBrowse Home | New Git URL