django - 表单提交后 Django 发送两次电子邮件
问题描述
我试图在我的应用程序中提交表单时发送电子邮件,我设法做到了,但由于某种原因,它每次发送两次。经过一番搜索和调试,我想我知道问题出在哪里,但我不知道为什么。
所以我的应用程序的电子邮件发送功能发生在我的表单中。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() 函数运行了 2 次。我试图将电子邮件发送函数移动到 form_valid() 函数中的 views.py ,但它从未被调用,所以我尝试了 form_invalid() 但结果相同。
有什么办法不让 save() 函数运行 2 次?或者这是因为我的代码中的一些错误?
解决方案
当覆盖 save() 方法时,您应该在最后调用 super()。
此外,在有效保存您的实例之前,仅应使用覆盖此方法来添加对其他事物的一些检查。在这里,我看到您在 save() 方法中对实例执行了 save()。
您的实例上的有效保存(),这里是“自我”,应该只通过 super() 完成一次
并且在覆盖 save() 时无需返回任何内容。只需使用 super() 完成,一切都会好起来的。
推荐阅读
- json - 打字稿中 fs.writeFileSync 输出的 JSON 文件的最大大小是多少
- c# - 在回发时保持手风琴状态
- gmail - 使用 Mailkit 从谷歌下载电子邮件,因为纯/文本每 78 个(可能)字符就断行
- woocommerce - 如何在类别页面上动态显示产品类别名称
- regex - 正则表达式难以过滤结果
- javascript - 登出时服务器不可达怎么办
- python - 如何在 Python 中将问题和分数放在一起
- java - 从 firebase 数据库获取数据时,期望开始数组时出错
- ssl - Certbot 自动配置后站点未启用 ssl
- mysql - 使用 Spring Boot JPA 在数据库中插入多行