Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django在提交表单后发送两次电子邮件_Django_Django Forms_Django Email - Fatal编程技术网

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

Django在提交表单后发送两次电子邮件,django,django-forms,django-email,Django,Django Forms,Django Email,在我的应用程序中提交表单时,我试图发送电子邮件,我成功地做到了这一点,但由于某种原因,它每次发送两次。 经过一些搜索和调试,我想我知道问题出在哪里,但我不知道为什么 因此,我的应用程序的电子邮件发送功能发生在我的表单中。py,看起来像这样: class approvalForm(forms.ModelForm): text1 = forms.ModelChoiceField(disabled = True, queryset = Visit.objects.all()) text

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

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


有没有办法不让save函数运行两次?或者这是因为我的代码中有错误吗?

当重写save方法时,应该在最后调用super

此外,在有效保存实例之前,重写此方法只应用于添加对其他内容的一些检查。在这里,我看到您在save方法中对实例..执行save操作

在您的实例上的有效保存(这里是“self”)应该只通过超级用户执行一次

并且在重写save时不需要返回任何内容。只要完成super,一切都会好起来。

尝试将保存方法更改为:

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()

您正在保存实例2:为什么默认情况下通过super.save检索实例而不提交?为什么你有一个其他的:没有??如果ready为True:可以写为:如果ready:这解决了问题,谢谢!现在在控制台中,我只看到一个打印!但它也给了我一个错误:“NoneType”对象没有属性“dict”。我不确定这意味着什么:@ Vestelutto请考虑将它标记为接受,如果它解决了你的问题。你的另一个问题似乎是与其他事物有关。