Django 在提交表单后发送两次电子邮件

Django sends emails twice after form submission

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

所以我的应用程序的电子邮件发送功能发生在我的表单中。 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() 函数 运行ning 2 次。我试图将电子邮件发送功能移动到 form_valid() 函数中的 views.py 但它从未被调用所以我尝试了 form_invalid() 但结果相同。

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

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

此外,覆盖此方法应该仅用于在有效保存实例之前添加一些其他内容的检查。在这里我看到你在实例上做了一个 save() ..在 save() 方法中。

您实例上的有效 save(),此处为 'self',应该仅通过 super()

完成一次

并且在覆盖 save() 时不需要 return 任何东西。只需完成 super() ,一切都会好起来的。

尝试将您的 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()