欢迎来到Felix的博客

Do the right things! And talk is cheap,show me your code!

搭建自己的博客(三十一):为评论以及回复添加邮箱提醒

1、变化的部分:

2、上代码

from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
from django.contrib.contenttypes.fields import GenericRelation
from ckeditor_uploader.fields import RichTextUploadingField
from django.contrib.contenttypes.models import ContentType
from read_statistics.models import ReadNumExpandMethod, ReadDetail


# Create your models here.

# 博客分类
class BlogType(models.Model):
    type_name = models.CharField(max_length=15)  # 博客分类名称

    def __str__(self):  # 显示标签名
        return self.type_name


# 博客
class Blog(models.Model, ReadNumExpandMethod):
    title = models.CharField(max_length=50)  # 博客标题
    blog_type = models.ForeignKey(BlogType, on_delete=models.CASCADE)  # 博客分类
    content = RichTextUploadingField()  # 博客内容,使用富文本编辑
    author = models.ForeignKey(User, on_delete=models.CASCADE)  # 博客作者
    read_details = GenericRelation(ReadDetail)  # 关联到阅读表
    created_time = models.DateTimeField(auto_now_add=True)  # 博客创建时间
    last_updated_time = models.DateTimeField(auto_now=True)  # 博客更新事件

    def get_url(self):  # 获取博客的url路径
        return reverse('blog_detail', kwargs={'blog_pk': self.pk})

    def get_email(self):  # 获取博客作者的邮箱
        return self.author.email

    def __str__(self):  # 显示标题名
        return "<Blog:{}>".format(self.title)

    class Meta:
        ordering = ['-created_time']  # 定义排序规则,按照创建时间倒序
blog下的models.py
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>评论提醒</title>
</head>
<body>

<p>评论或回复内容:<br>
    {{ comment_text|safe }}
    <br>
    博客链接:
    <br>
    <a href="{{ url }}">点击查看</a>
</p>
</body>
</html>
send_mail.html
import threading
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.auth.models import User
from django.conf import settings
from django.template.loader import render_to_string
from myblog.utils import AutoSendEmail


class SendEmail(threading.Thread):
    def __init__(self, title, email, comment_content, blog_url):
        self.title = title
        self.email = email
        self.comment_content = comment_content
        self.blog_url = blog_url
        super().__init__()

    def run(self):
        auto_email = AutoSendEmail(sender=settings.EMAIL_HOST_USER, recever=[self.email],
                                   password=settings.EMAIL_HOST_PASSWORD, title=self.title,
                                   from_who=settings.FROM_WHO,
                                   smtp_server=settings.MAIL_HOST, port=settings.EMAIL_PORT)

        html = render_to_string('comment/send_mail.html',{'comment_text':self.comment_content,'url':self.blog_url})
        # 以html的形式发送文字,推荐这个,因为可以添加图片等
        auto_email.addHtml(html)
        # 发送邮件
        try:
            auto_email.sendEmail()
        except Exception as e:
            print(str(e))


class Comment(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    text = models.TextField()
    comment_time = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User, related_name='comments', on_delete=models.CASCADE)

    root = models.ForeignKey('self', related_name='root_comment', null=True, on_delete=models.CASCADE)
    # 两个外键关联同一个表时,通过related_name来解决冲突
    parent = models.ForeignKey('self', related_name='parent_comment', null=True, on_delete=models.CASCADE)
    reply_to = models.ForeignKey(User, related_name='replies', on_delete=models.CASCADE, null=True)

    def send_email(self):

        # 评论之后发送邮件通知
        if self.parent is None:
            # 评论博客
            email = self.content_object.get_email()
            title = '有人评论你的博客'
        else:
            # 回复评论
            email = self.reply_to.email  # 被回复的人的邮箱
            title = '有人回复你的博客'

        if email != '':
            comment_content = self.text
            blog_url = self.content_object.get_url()
            send__email = SendEmail(title, email, comment_content, blog_url)
            send__email.start()

    def __str__(self):
        return self.text

    class Meta:
        ordering = ['comment_time']
models.py
from django.http import JsonResponse

from django.contrib.contenttypes.models import ContentType
from .models import Comment
from .forms import CommentForm


def update_commit(requests):
    comment_form = CommentForm(requests.POST, user=requests.user)
    if comment_form.is_valid():
        comment = Comment()
        comment.user = comment_form.cleaned_data['user']
        comment.text = comment_form.cleaned_data['text']
        comment.content_object = comment_form.cleaned_data['content_object']

        parent = comment_form.cleaned_data['parent']
        if parent is not None:
            comment.root = parent.root if parent.root is not None else parent
            comment.parent = parent
            comment.reply_to = parent.user
        comment.save()
        # 发送邮件通知
        comment.send_email()
        # 返回数据
        data = {
            'status': 'SUCCESS',
            'username': comment.user.get_nickname_or_username(),
            'comment_time': comment.comment_time.timestamp(),  # 返回时间戳
            'text': comment.text.strip(),
            'reply_to': comment.reply_to.get_nickname_or_username() if parent is not None else '',
            'pk': comment.pk,
            'root_pk': comment.root.pk if comment.root is not None else '',
            'content_type': ContentType.objects.get_for_model(comment).model,
        }

    else:
        data = {
            'status': 'ERROR',
            'message': list(comment_form.errors.values())[0][0],
        }
    return JsonResponse(data)
views.py

 

from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
from django.contrib.contenttypes.fields import GenericRelation
from ckeditor_uploader.fields import RichTextUploadingField
from django.contrib.contenttypes.models import ContentType
from read_statistics.models import ReadNumExpandMethod, ReadDetail


# Create your models here.

# 博客分类
class BlogType(models.Model):
type_name = models.CharField(max_length=15) # 博客分类名称

def __str__(self): # 显示标签名
return self.type_name


# 博客
class Blog(models.Model, ReadNumExpandMethod):
title = models.CharField(max_length=50) # 博客标题
blog_type = models.ForeignKey(BlogType, on_delete=models.CASCADE) # 博客分类
content = RichTextUploadingField() # 博客内容,使用富文本编辑
author = models.ForeignKey(User, on_delete=models.CASCADE) # 博客作者
read_details = GenericRelation(ReadDetail) # 关联到阅读表
created_time = models.DateTimeField(auto_now_add=True) # 博客创建时间
last_updated_time = models.DateTimeField(auto_now=True) # 博客更新事件

def get_url(self): # 获取博客的url路径
return reverse('blog_detail', kwargs={'blog_pk': self.pk})

def get_email(self): # 获取博客作者的邮箱
return self.author.email

def __str__(self): # 显示标题名
return "<Blog:{}>".format(self.title)

class Meta:
ordering = ['-created_time'] # 定义排序规则,按照创建时间倒序
posted @ 2018-11-30 16:16  寂静的天空  阅读(255)  评论(0编辑  收藏  举报
个人感悟: 一个人最好的镜子就是自己,你眼中的你和别人眼中的你,不是一回事。有人夸你,别信;有人骂你,别听。一根稻草,扔街上就是垃圾;捆上白菜就是白菜价;捆上大闸蟹就是大闸蟹的价。 一个人,不狂是没有出息的,但一直狂,肯定是没有出息的。雨打残花风卷流云,剑影刀光闪过后,你满脸冷酷的站在珠峰顶端,傲视苍生无比英武,此时我问你:你怎么下去? 改变自己就是改变自己的心态,该沉的时候沉下去,该浮的时候浮上来;不争名夺利,不投机取巧,不尔虞我诈;少说、多听、多行动。人每所谓穷通寿夭为命所系,岂不知造物之报施,全视人之自取。 座佑铭:每一个不曾起舞的日子,都是对生命的辜负。