在 django EmailMultiAlternatives 模板中显示不同的用户名

Display defferent usernames in django EmailMultiAlternatives template

如果我想通过 EmailMultiAlternativesDjango[= 发送电子邮件,如何在模板正文中显示不同的 username 24=]。我有几个电子邮件接收者。 这是我的代码:

models.py:

class User(AbstractUser):
    category = models.ForeignKey('news.Category', on_delete=models.CASCADE,
                                 related_name='subscribers', null=True)


class Category(models.Model):
category = models.CharField(unique=True, max_length=255)


class Post(models.Model):
NEWS = 'NEWS'
POST = 'POST'
type_choice = [(NEWS, 'Nowost'), (POST, 'Post')]

author = models.ForeignKey('accounts.Author', on_delete=models.CASCADE)
date_of_creation = models.DateTimeField(auto_now_add=True)
text_content = models.TextField()
rating = models.IntegerField(default=0)
header = models.CharField(max_length=255)
category = models.ManyToManyField(Category, through='PostCategory')
type_of_content = models.CharField(max_length=4, choices=type_choice, default=NEWS)

signals.py

    @receiver(m2m_changed,  sender=Post.category.through)
def notify_subscribers(sender, instance, action,**kwargs):
    if action == 'post_add':
        email_of_subscribers = list(instance.category.all().values_list('subscribers__email', flat=True))
        html_content = render_to_string(
            r'mails_forms/post_created.html',
            {'single_news': instance
            }
        )
        msg = EmailMultiAlternatives(
            subject=instance.header,
            body=instance.text_content,
            to=email_of_subscribers
        )
        msg.attach_alternative(html_content, 'text/html')
        msg.send()

模板mails_forms/post_created.html

    Hello, {{ username }}. New post in your favorite category!
{{ single_news.text_content|truncatechars:50 }}
<a href="http://127.0.0.1:8000{% url 'single_news' single_news.id %}">Open post</a>

您可以迭代 subscribers。而不是 values_list('subscribers__email', flat=True) 使用 values('subscribers__email', 'subscribers__username')

@receiver(m2m_changed,  sender=Post.category.through)
def notify_subscribers(sender, instance, action,**kwargs):
    if action == 'post_add':
        subscribers = instance.category.<b>values(
            'subscribers__email', 'subscribers__username'
        )</b>
        for subscriber in subscribers:
            html_content = render_to_string(
                'mails_forms/post_created.html',
                {
                     'single_news': instance, 
                     <b>'username': subscriber.get("subscribers__username")</b>
                }
            )
            msg = EmailMultiAlternatives(
                subject=instance.header,
                body=instance.text_content,
                to=[subscriber.get("subscribers__email")]
            )
            msg.attach_alternative(html_content, 'text/html')
            msg.send()