搭建本身的博客(三十一):爲評論以及回覆添加郵箱提醒

一、變化的部分:html

二、上代碼django

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'] # 定義排序規則,按照建立時間倒序
相關文章
相關標籤/搜索