Search code examples
pythondjangosendgrid-api-v3

'in <string>' requires string as left operand, not BoundWidget sendgrid


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

.env file

SENDGRID_API_KEY=XXXXXXXXXXXXXXXXXXXX

settings.py

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

views.py

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


Solution

  • 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']