我有一个旨在禁止用户然后将它们添加到Banned_User
表格的功能。那么我可以向用户发送一封电子邮件,其中包含禁令的详细信息。但我似乎无法忍受获得禁止和保存的功能
当前回溯错误:异常类型:/ admin / api / profile /中的TypeError 例外值:禁止直接分配到多对多集的前端。请改用report_reason.set()。
def banning_users(self, request, queryset):
for obj in queryset:
if hasattr(obj, 'user'):
# This object is a Profile, so lookup the user
profile = obj
user = obj.user
user.is_active = False
user.save()
# Get the report(s) for this user
user_reports = Report.objects.filter(user_reported=profile)
# Go through each report, in case there are multiples,
# add a record in the ban table
banned_reasons = []
for report in user_reports:
ban_record = Banned_User.objects.create(profile=profile, report_reason=report)
ban_record.save()
banned_reasons.append(report.get_report_reason_display())
# Send the email
subject = 'Ban'
message = 'You have been banned for the following reasons: []' + \
report.report_reason + banned_reasons[0] + banned_reasons[1]
email_from = settings.EMAIL_HOST_USER
recipient_list = [user.email]
send_mail( subject, message,email_from, recipient_list)
self.message_user(request, "User is banned and Email has been sent")
BANNED_USER模型
class Banned_User(models.Model):
def __str__(self):
return str.join(str(self.profile), str(self.report_reason.report_reason))
#return self.profile
#return str.join(str(self.profile), str(self.report_reason))
profile = models.ForeignKey(
'Profile',
on_delete=models.PROTECT,
blank=False,
null=False,
related_name='banned_profile'
)
report_reason = models.ManyToManyField(
'Report',
#on_delete=models.PROTECT,
blank=True,
#null=True,
)
date_banned = models.DateField(null=True, blank=False,)
报告模型
class Report(models.Model):
def __str__(self):
return str.join(str(self.user_reported), str(self.datetime_sent))
TOXICITY = 'Toxicity'
SPORTSMANSHIP = 'Poor sportsmanship'
REPORT_REASON_CHOICES = (
(TOXICITY, 'Toxicity'),
(SPORTSMANSHIP, 'Unsportsmanlike Behaviour'),
)
session = models.ForeignKey(
'Session',
on_delete=models.PROTECT,
blank=False,
null=False,
)
user_reported = models.ForeignKey(
'Profile',
on_delete=models.PROTECT,
blank=False,
null=False,
related_name='user_reported_report',
)
sent_by = models.ForeignKey(
'Profile',
on_delete=models.PROTECT,
blank=False,
null=False,
related_name='sent_by_report',
)
report_reason = models.CharField(
max_length=255,
choices=REPORT_REASON_CHOICES,
default=TOXICITY,
)
datetime_sent = models.DateTimeField(auto_now_add=True,)
答案 0 :(得分:1)
报告失败的原因是您尝试将外键分配给设置为要求使用add命令的多对多字段。
ban_record = Banned_User.objects.create(profile=profile, report_reason=report)
哪个不行。您需要做的是为Profile
创建banned_user模型banned_user = profile.banned_profile.create(profile=profile)
然后你会为禁止用户添加禁令 编辑
reports = banned_user.profile.user_reported_report.all()
for report in reports:
banned_user.report_reason.add(report)
您可以在这里查看使用多对多文件。 https://docs.djangoproject.com/en/2.0/topics/db/examples/many_to_many/