2

为什么我收到 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
4

4 回答 4

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

但不是进口的,进口吧。

于 2012-05-14T02:08:42.207 回答
1

在项目 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/

于 2020-02-10T23:53:48.613 回答
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)

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

于 2012-05-14T01:56:33.980 回答
0

NameError:未定义名称“send_mail”

from django.core.mail import send_mail
于 2020-05-20T09:19:27.227 回答