'in <string>'需要将字符串作为左操作数,而不是BoundWidget sendgrid

时间:2019-10-22 10:30:26

标签: python django sendgrid-api-v3

我正在使用Django Web应用程序。我有联系我们表格。当用户提交表单时,表单中的消息将作为邮件发送到预定义的电子邮件ID。

我使用sendgrid来发送电子邮件。为此,我创建了一个帐户并生成了一个api。我将api密钥存储在dotenv文件中,并在settings.py文件中访问api

.env文件

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)

但是当我提交表单时,我收到了此错误消息

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

我不知道我哪里出了错。

这是我跟随link发送带有sendgrid的电子邮件

1 个答案:

答案 0 :(得分:1)

您正在访问字段本身,而不是已验证的数据。您需要:

firstName = ContactUsForm.cleaned_data['firstName']
fromEmail = ContactUsForm.cleaned_data['email']
message = ContactUsForm.cleaned_data['message']