0

我正在尝试将时事通讯作为电子邮件发送给订阅用户。为此,我做了:

我在我的模型中创建了一个自定义 send_mail() 函数来向订阅用户发送电子邮件

class Post(models.Model):

    'model fields here'


    def __str__(self):
        return self.title + ' by ' + self.author


    def send_mail(self, request):
        content = self.content
        title = self.title
        slug = self.slug
        series_name = self.series_name
        confirmed_subscribers = Subscriber.objects.values_list('email').filter(confirmed=True)
        current_site = get_current_site(request)
        subject = "New Blog - '" + title + "' @ AM-Blogs!!"
        message = render_to_string('new_post.html',{
                'title': title,
                'content': content,
                'slug': slug,
                'series_name': series_name,
                'domain': current_site.domain,
            })

        for sub in confirmed_subscribers:

            email = EmailMessage(
            subject,
            message,
            settings.EMAIL_HOST_USER,
            [sub],
            )
            email.fail_silently = True
            email.send()

        return redirect ('Home')

然后,在 admin.py 中:

class PostAdmin(admin.ModelAdmin):

    class Media:
        js = ('tinyInject.js',)

    actions = ['send_mail']

    def send_mail(self, request, queryset):
        for post in queryset:
            post.send_mail(request)
    send_mail.short_description = "Send selected Newsletters to all subscribers"




admin.site.register(Post, PostAdmin)

当我进入我的管理面板并执行操作时:

错误:

ValueError at /admin/blog/post/
not enough values to unpack (expected 2, got 1)

突出显示的错误:

D:\My_Projects\My-Blog\blog\admin.py in send_mail
            post.send_mail(request) …
▶ Local vars
D:\My_Projects\My-Blog\blog\models.py in send_mail
            email.send() …
▶ Local vars

我该如何解决这个问题?请帮忙!!

4

1 回答 1

0

好的!!我自己解决了。这里唯一的错误是'to_email'(电子邮件的接收者) - 订阅者本身就是一个列表。

代码应该是这样的:

emailsub = EmailMessage(
                subject,
                message,
                settings.EMAIL_HOST_USER,
                sub,
                )

代替:

emailsub = EmailMessage(
                subject,
                message,
                settings.EMAIL_HOST_USER,
                [sub],
                )

谢谢你!!

于 2020-05-27T10:29:23.167 回答