Django views.py逻辑未按要求发送电子邮件

时间:2020-06-20 04:18:51

标签: django

我已经编写了此视图逻辑,以便在将内容保存为等于“已发布”后将其作为新闻稿发送电子邮件,但是它仅保存而不发送电子邮件。

我知道电子邮件配置是正确的,因为我在订阅时会收到电子邮件

我无法弄清楚views.py的逻辑错误

def control_newsletter(request):
    form = NewsletterCreationForm(request.POST or None)

    if form.is_valid():
        instance = form.save()
        newsletter = Newsletter.objects.get(id=instance.id)
        if newsletter.status == "Published":
            subject = newsletter.subject
            body = newsletter.body
            from_email = settings.EMAIL_HOST_USER
            for email in newsletter.email.all():
                send_mail(subject=subject, from_email=from_email, recipient_list=[
                          email], message=body, fail_silently=False)
    context = {
        "form": form,
    }
    template = 'control_newsletter.html'
    return render(request, template, context)

这是模型。py

class NewsletterUser(models.Model):
    email = models.EmailField()
    date_added = models.DateTimeField(default=timezone.now)

    class Meta:
        verbose_name = "Newsletter User"

    def __str__(self):
        return self.email


class Newsletter(models.Model):
    EMAIL_STATUS_CHOICES = (
        ('Draft', 'Draft'),
        ('Published', 'Published')
    )
    subject = models.CharField(max_length=250)
    body = models.TextField()
    email = models.ManyToManyField(NewsletterUser)
    status = models.CharField(max_length=10, choices=EMAIL_STATUS_CHOICES)
    created = models.DateTimeField(default=timezone.now)
    updated = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.subject

这是表格。py

class NewsletterUserSignupForm(forms.ModelForm):
    helper = FormHelper()
    helper.form_show_labels = False

    class Meta:
        model = NewsletterUser
        fields = ['email']

        def clean_email(self):
            email = self.cleaned_email.get('email')

            return email


class NewsletterCreationForm(forms.ModelForm):
    class Meta:
        model = Newsletter
        fields = ['subject', 'body', 'email', 'status']

0 个答案:

没有答案