Search code examples
djangodjango-formsdjango-email

Django sends emails twice after form submission


I was trying to send emails when a form is submitted in my app, and I managed to do it but for some reason, it sends it twice every time. After some search and debugging I think I know where the problem is but I don't know why.

So the email sending function of my app takes place in my forms. py and looks like this:

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', )

The save() function is running 2 times. I've tried to move the email sending function to the views.py in the form_valid() function but it's never called so I've tried the form_invalid() but the same results.

Is there any way to not let the save() function run 2 times? Or is this because of some error in my code?


Solution

  • Try and change your save() method to this:

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