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

Django封禁用户后发送含封禁原因邮件的技术求助

解决邮件中封禁原因列表为空的问题

你的问题核心在于邮件内容是硬编码的空列表,没有把实际的封禁原因动态填充进去。我们只需要提取用户对应的举报原因,再格式化插入到邮件里就行,下面是修改后的完整方案:

修改后的封禁函数代码

from django.utils import timezone

def banning_users(self, request, queryset): #BANNING FUNCTION
    for obj in queryset:
        if hasattr(obj, 'user'):
            profile = obj
            user = obj.user
            user.is_active = False
            user.save()
            
            # 创建Banned_User记录并补全封禁日期
            banned_user = profile.banned_profile.create(
                profile=profile,
                date_banned=timezone.now().date()
            )
            reports = banned_user.profile.user_reported_report.all()
            
            # 收集所有举报的友好显示原因
            report_reasons = [report.get_report_reason_display() for report in reports]
            
            # 批量关联举报记录到Banned_User
            banned_user.report_reason.add(*reports)
            banned_user.save()
            
            # 构建带原因的邮件内容
            subject = 'Account Ban Notification'
            if report_reasons:
                # 把原因格式化成易读的项目列表
                formatted_reasons = '\n- '.join(report_reasons)
                message = f'Your account has been banned for the following reasons:\n- {formatted_reasons}'
            else:
                message = 'Your account has been banned. No specific reasons were provided.'
            
            email_from = settings.EMAIL_HOST_USER
            recipient_list = [user.email]
            send_mail(subject, message, email_from, recipient_list)
    
    self.message_user(request, "Selected users have been banned and notification emails sent")

关键修改点说明

  1. 动态收集举报原因:

    • 用report.get_report_reason_display()获取Report模型中report_reason字段的友好显示文本(比如拿到"Unsportsmanlike Behaviour"而不是数据库里存的"SPORTSMANSHIP")。
    • 把所有原因存入列表,方便后续格式化。
  2. 格式化邮件内容:

    • 替换了原代码中硬编码的空列表[],根据是否有原因生成对应的邮件文本:有原因就做成项目符号列表,没有就显示默认提示。
  3. 优化数据操作:

    • 创建banned_user时直接设置date_banned(模型里该字段要求非空),避免数据库报错。
    • 用banned_user.report_reason.add(*reports)一次性添加所有举报,比循环逐个添加更高效。
  4. 细节优化:

    • 把邮件主题改成更清晰的"Account Ban Notification",让用户一眼明白邮件用途。
    • 最后提示文本也做了优化,更严谨。

额外提醒

  • 确保你的settings.py已经正确配置了邮件发送参数(EMAIL_HOST、EMAIL_PORT等),不然邮件发不出去。
  • 如果存在重复的举报原因,可以用list(set(report_reasons))去重后再生成邮件内容(注意顺序需求的话可以用有序集合)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 03:59:33