You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django评论邮件通知问题:需补充用户名及评论内容字段

表单提交后邮件通知无法获取用户名和评论内容的问题

我正在实现表单提交后发送邮件通知的功能,需要包含用户的用户名及评论内容。目前已成功在邮件中显示文章标题,但其他内容无法正常获取,寻求技术帮助。

视图(Views)

def ViewPost(request, slug):
        try:
            post = BlogPost.objects.get(slug=slug)
        except BlogPost.DoesNotExist: 
            print("Blog with this slug does not exist")
            post = None
    
    
        comments = post.comments.filter(status=True)
        user_comment = None
    
        if request.method == 'POST':
            comment_form = CommentForm(request.POST)
            if comment_form.is_valid():
                user_comment = comment_form.save(commit=False)
                user_comment.post = post
                user_comment.user = request.user
                user_comment.save()
               
                messages.success(request, ("Comment successfully posted, thank you..."))
                send_mail('You have recieved a comment on a blog post', post.title, post.user # not working , #reference comment here 
                [
                    'gmail.com'])
              
        else:
            comment_form = CommentForm()
    
        
        return render(request, 'mhpapp/view-post.html', {'post': post, 'slug': slug, 'comments': user_comment, 'comments': comments, 'comment_form': comment_form})

评论模型(Comment Model)

class BlogComment(models.Model):
    post = models.ForeignKey(BlogPost, related_name="comments", on_delete=models.CASCADE)
    user = models.ForeignKey(User, editable=False, on_delete=models.CASCADE, default="",)
    name = models.CharField('Name',max_length=100, default="")
    text = models.TextField('Comment',max_length=1000, default="")
    date = models.DateTimeField(auto_now_add=True)
    status = models.BooleanField(default=True)

    class Meta:
            ordering = ("date",) 

    def __str__(self):
        return '%s -> %s'%(self.post.title, self.user)

解决方案

核心问题与修正

你的send_mail调用存在参数顺序错误、内容拼接缺失的问题,同时视图上下文有重复键值的小问题,以下是修正后的完整关键代码:

def ViewPost(request, slug):
    try:
        post = BlogPost.objects.get(slug=slug)
    except BlogPost.DoesNotExist: 
        print("Blog with this slug does not exist")
        post = None

    comments = post.comments.filter(status=True) if post else []
    user_comment = None

    if request.method == 'POST':
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            user_comment = comment_form.save(commit=False)
            user_comment.post = post
            user_comment.user = request.user
            user_comment.save()
           
            messages.success(request, "Comment successfully posted, thank you...")
            # 构建包含完整信息的邮件内容
            email_subject = "You have received a comment on a blog post"
            email_body = f"""
            New comment on your blog post: {post.title}
            
            Commenter: {request.user.username}
            Comment content: {user_comment.text}
            """
            # 正确调用send_mail,参数顺序为:主题、正文、发件人、收件人列表
            send_mail(
                email_subject,
                email_body,
                # 替换为你的发件邮箱,或使用settings.DEFAULT_FROM_EMAIL
                "your-sender-email@example.com",
                ["recipient-email@example.com"]
            )
    else:
        comment_form = CommentForm()

    # 修复上下文重复键的问题,将新评论单独传递
    return render(request, 'mhpapp/view-post.html', {
        'post': post, 
        'slug': slug, 
        'new_comment': user_comment, 
        'comments': comments, 
        'comment_form': comment_form
    })

关键修改说明

  1. 邮件内容拼接:使用f-string将文章标题、评论者用户名(request.user.username)、评论内容(user_comment.text)整合到邮件正文中,确保信息完整。
  2. send_mail参数修正:Django的send_mail函数正确参数顺序为主题, 正文, 发件人邮箱, 收件人列表,你之前的参数顺序混乱导致内容无法正确传递。
  3. 上下文重复键修复:原代码中'comments': user_comment和'comments': comments重复,后者会覆盖前者,改为'new_comment': user_comment避免冲突。
  4. 空值处理:添加comments = post.comments.filter(status=True) if post else [],避免post为None时触发异常。

内容的提问来源于stack exchange,提问作者David Henson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 04:15:37