我正在尝试实施简报并在我的UserProfile类中添加一个选择字段,让用户选择是否要收到简报:
class UserProfile(models.Model):
user = models.OneToOneField(User)
YES = 'YS'
NO = 'NO'
NEWS_CHOICES = (
(YES, 'Yes'),
(NO, 'No'),
)
newsletter = models.CharField(max_length=2, choices= NEWS_CHOICES, default=NO)
我提出这个观点是向想要收到简报的用户发送简报(选择'是'):
@user_passes_test(lambda u: u.is_superuser)
def newsletter_form(request):
if request.method == 'POST':
form = NewsletterForm(request.POST or None, request.FILES or None)
if form.is_valid():
reader = UserProfile.objects.filter(newsletter='YS')
instance = form.save(commit=False)
instance.save()
subject = 'This is the Newsletter!'
message = 'Hello!'
from_email = settings.EMAIL_HOST_USER
to_list = [reader.user.email]
html_message = loader.render_to_string('gaestebuch/newsletter.html')
send_mail(subject, message, from_email, to_list, fail_silently = True, html_message=html_message)
return redirect('gaestebuch:index')
else:
print form.errors
else:
form = NewsletterForm()
context = {'form': form}
return render(request, 'gaestebuch/newsletter_form.html', context)
我很满意:
to_list = [reader.user.email]
我得到的错误是:
'QuerySet' object has no attribute 'user'
如果有人能在这一点上帮助我,我会很高兴:)
答案 0 :(得分:1)
如错误所示,reader
是一个查询集,但您似乎将其视为UserProfile
的单个实例。这应该可以将所有收件人添加到列表中:
to_list = [r.user.email for r in reader]
请注意following part of the documentation(强调我的):
recipient_list
:字符串列表,每个字符串都是一个电子邮件地址。recipient_list
的每位成员都会在电子邮件的“收件人:”字段中看到其他收件人。
如果您不希望所有收件人互相看到,那么您需要为每个收件人发送单独的邮件。