繁体   English   中英

NameError Django send_mail

[英]NameError django send_mail

为什么我收到 NameError: global name 'send_mail' is not defined

从我的models.py:

from django.template import Context, loader
from django.utils.translation import ugettext as _
from django.core.mail import send_mail
.......
class Payment(models.Model):    

    # send email for payment
    # 1. render context to email template
    email_template = loader.get_template('classifieds/email/payment.txt')
    context = Context({'payment': self})
    email_contents = email_template.render(context)

    # 2. send email
    send_mail(_('Your payment has been processed.'),
              email_contents, settings.FROM_EMAIL,
              [self.ad.user.email], fail_silently=False)

谢谢!

Traceback:
File "/home/.../webapps/django/lib/python2.7/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/home/.../webapps/django/lib/python2.7/django/views/decorators/csrf.py" in wrapped_view
  77.         return view_func(*args, **kwargs)
File "/home/.../webapps/django/myproject/classifieds/views/create.py" in checkout
  122.       send_mail(_('Your ad will be posted shortly.'),

Exception Type: NameError at /checkout/2
Exception Value: global name 'send_mail' is not defined

回溯来自您的观点。

File "/home/.../webapps/django/myproject/classifieds/views/create.py" in checkout
  122.       send_mail(_('Your ad will be posted shortly.'),

您发布了模型中的代码。

我认为classifieds/views/create.py没有导入 send_mail。

另一个问题是为什么你在你的模型类上做这些事情而不是......在模型方法中......

编辑:你把它放在问题中的方式让它看起来非常奇怪,这个发送邮件的东西是在类上而不是在方法中发生的。 查看源码,你看到它在Payment.complete方法中: https : //github.com/saebyn/django-classifieds/blob/master/classifieds/models.py#L273

send_mail在这里使用: https : //github.com/saebyn/django-classifieds/blob/master/classifieds/views/create.py#L116

但不是进口的,进口吧。

在项目 settings.py 中使用这些:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'yourusername'
EMAIL_HOST_PASSWORD = 'YourPassword'
EMAIL_PORT = 587
EMAIL_USE_TLS = True

在您的控制器中使用:

from django.core.mail import send_mail

send_mail('Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False)

以供参考:

https://sendgrid.com/docs/for-developers/sending-email/django/

尝试将您的 send_mail 函数替换为:

django.core.mail.send_mail(your_parameters)

此外,您在 send_mail 中的第一个参数似乎不是字符串,请更改为以下内容:(https://docs.djangoproject.com/en/dev/topics/email/?from=olddocs)

send_mail('Your payment has been processed.',
              email_contents, settings.FROM_EMAIL,
              [self.ad.user.email], fail_silently=False)

尝试这两个建议,让我知道你得到了什么。

NameError:未定义名称“send_mail”

from django.core.mail import send_mail

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM