I am working on a django web application. I have a contact us form. when a user submits the form, the message in the form is sent as a mail to a predefined email id.
For sending the email, I am using sendgrid. I created an account and generated an api for this purpose. I stored the api key in a dotenv file and access the api in the settings.py file
SENDGRID_API_KEY=XXXXXXXXXXXXXXXXXXXX
import os
from dotenv import load_dotenv
load_dotenv()
...
EMAIL_BACKEND = "sendgrid_backend.SendgridBackend"
SENDGRID_API_KEY = os.environ.get("SENDGRID_API_KEY")
SENDGRID_SANDBOX_MODE_IN_DEBUG=False
def index(request):
if request.method == "POST":
ContactUsForm = ContactUs(request.POST)
if ContactUsForm.is_valid():
firstName = ContactUsForm['firstName']
fromEmail = ContactUsForm['email']
message = ContactUsForm['message']
send_mail(subject=f"{firstName} sent you a message", message=message, from_email=fromEmail, recipient_list=['toaddress@email.com'])
return redirect('home')
else:
ContactUsForm = ContactUs()
context = {'contactUs': ContactUsForm}
return render(request, 'index.html', context)
But when I submit the form, I get this error message
TypeError: 'in <string>' requires string as left operand, not BoundWidget
I dont know where I went wrong.
This is the link I followed to send emails with sendgrid
You're accessing the fields themselves, instead of the validated data. You need:
firstName = ContactUsForm.cleaned_data['firstName']
fromEmail = ContactUsForm.cleaned_data['email']
message = ContactUsForm.cleaned_data['message']