为什么我会收到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
答案 0 :(得分:2)
回溯来自您的观点。
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
但未导入,请将其导入。
答案 1 :(得分:1)
在项目设置中使用它们。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)
供参考:
答案 2 :(得分:0)
尝试使用以下命令替换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)
尝试这两个建议,让我知道你得到了什么。
答案 3 :(得分:0)
NameError:未定义名称“ send_mail”
from django.core.mail import send_mail