Send email based on form boolean value

I am trying to send email based on the form boolean value. If the Trigger_Email is True then send the mail

Below is the models.py

class New_Shipment(models.Model):
    Status_CHOICES = (
        ("1", "Open"),
        ("2", "Close"),

    )

    alphanumeric = RegexValidator(r'^[\s0-9a-zA-Z\.-_]*$', 'Only alphanumeric characters are allowed.')
    Courier_or_Freight_details = models.CharField(max_length=200, validators=[alphanumeric])
   
    Quantity = models.IntegerField()
    Action_On = models.CharField(max_length=200, validators=[alphanumeric])
    Status = models.CharField(max_length=300, validators=[alphanumeric], choices=Status_CHOICES)
    Trigger_Email = models.BooleanField(default=False)

Below is my views.py

def my_form1(request, new_shipment=New_Shipment):
    if request.method == "POST":
        form1 = MyForm1(request.POST)
        if form1.is_valid():
            new_shipment = get_object_or_404(New_Shipment)
        elif new_shipment.Trigger_Email:
            subject = "New Shipment Details"
            message = "Hello \n New Shipment details added to the EPC\n\n Regards,\nIsmail"
            from_email = settings.EMAIL_HOST_USER
            to_list = ['toemail@gmail.com']
            send_mail(subject, message, from_email, to_list, fail_silently=True)


            form1.save()
            return HttpResponse('Submitted successfully')
            # return redirect('/home_page/')
    else:
        form1 = MyForm1()
    return render(request, "authentication/New_shipment.html", {'form1': form1})

Any Kind of help will be appreciated. Thanks in advance

Change elif to if inside form1.is_valid() condition.

Instead:

    if form1.is_valid():
        new_shipment = get_object_or_404(New_Shipment)
    elif new_shipment.Trigger_Email:
        subject = "New Shipment Details"
        ...

Do this:

    if form1.is_valid():
        new_shipment = get_object_or_404(New_Shipment)
        if new_shipment.Trigger_Email:
            subject = "New Shipment Details"
            ...
Back to Top