提交表单后,Dango发送了两次电子邮件

时间:2019-09-20 12:37:08

标签: django django-forms django-email

我试图在应用程序中提交表单时发送电子邮件,但我设法做到了,但是由于某种原因,它每次发送两次。 经过一些搜索和调试后,我想我知道问题出在哪里,但我不知道为什么。

因此,我的应用程序的电子邮件发送功能在我的表单中进行。 py,看起来像这样:

class approvalForm(forms.ModelForm):
    text1 = forms.ModelChoiceField(disabled = True, queryset = Visit.objects.all())
    text2 = forms.ChoiceField(disabled = True, choices = poolnumber)

def save(self, commit=False):
      instance = super(approvalForm, self).save(commit=commit)
      ready = instance.visible
      if ready is True:
        self.send_email()
        print('yay sent')
      else:
          None
      return instance

def send_email(self):
    var = self.cleaned_data
    tomail = self.cleaned_data.get('visit')
    tomails = tomail.location.users.all()
    tomaillist = []
    for item in tomails:
        tomaillist.append(item.email)
    print(tomaillist)
    msg_html = render_to_string('myapp/3email.html', {'notify': var})
    msg = EmailMessage(
          'Text here',
          msg_html,
          'myemail@email.com',
          tomaillist,
          headers={'Message-ID': 'foo'},
       )
    msg.content_subtype = "html"
    print("Email sent")
    msg.send() 


class Meta:
    model = MyModels
    fields = ('text1','text2', )

save()函数运行两次。我尝试将电子邮件发送功能移至form_valid()函数中的views.py,但从未调用过,所以我尝试了form_invalid()但结果相同。

有什么方法不让save()函数运行2次吗?还是这是因为我的代码有错误?

谢谢!

2 个答案:

答案 0 :(得分:1)

当覆盖save()方法时,您应该在最后调用super()。

此外,覆盖此方法仅应在有效保存实例之前仅添加对其他内容的某些检查。在这里,我看到您在save。)方法中的instance ..上执行了一次save()。

实例上的有效save()在这里是“ self”,应该只通过super()进行一次

并且覆盖save()时无需返回任何内容。只需完成super(),一切都会好起来的。

答案 1 :(得分:0)

尝试将您的save()方法更改为此:

def save(self, commit=True):  # declaration matches the method you are overriding
    instance = super(approvalForm, self).save(commit=False)
    ready = instance.visible
    if ready:   # no need to include is True
       self.send_email()
    if commit:
        instance.save()
相关问题