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")
关键修改点说明
动态收集举报原因:
- 用
report.get_report_reason_display()获取Report模型中report_reason字段的友好显示文本(比如拿到"Unsportsmanlike Behaviour"而不是数据库里存的"SPORTSMANSHIP")。 - 把所有原因存入列表,方便后续格式化。
- 用
格式化邮件内容:
- 替换了原代码中硬编码的空列表
[],根据是否有原因生成对应的邮件文本:有原因就做成项目符号列表,没有就显示默认提示。
- 替换了原代码中硬编码的空列表
优化数据操作:
- 创建
banned_user时直接设置date_banned(模型里该字段要求非空),避免数据库报错。 - 用
banned_user.report_reason.add(*reports)一次性添加所有举报,比循环逐个添加更高效。
- 创建
细节优化:
- 把邮件主题改成更清晰的"Account Ban Notification",让用户一眼明白邮件用途。
- 最后提示文本也做了优化,更严谨。
额外提醒
- 确保你的
settings.py已经正确配置了邮件发送参数(EMAIL_HOST、EMAIL_PORT等),不然邮件发不出去。 - 如果存在重复的举报原因,可以用
list(set(report_reasons))去重后再生成邮件内容(注意顺序需求的话可以用有序集合)。
内容的提问来源于stack exchange,提问作者Shadowwz
相关产品推荐
相关产品推荐

