搭建自己的博客(三十一):为评论以及回复添加邮箱提醒
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'] # 定义排序规则,按照创建时间倒序
<!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>
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']
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)
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'] # 定义排序规则,按照创建时间倒序