Python 名称错误django发送\u邮件

Python 名称错误django发送\u邮件,python,django,django-models,nameerror,Python,Django,Django Models,Nameerror,为什么会出现名称错误:未定义全局名称“发送邮件” 从my 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 #

为什么会出现名称错误:
未定义全局名称“发送邮件”

从my 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

尝试将“发送邮件”功能替换为:

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


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

回溯来自你的观点

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\u mail


但未导入,请导入。

在project 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)
供参考:


名称错误:未定义名称“发送邮件”

from django.core.mail import send_mail

你能发布完整的堆栈跟踪吗?它在那里的一个模型方法中。
send\u mail
的第一个参数是一个字符串,它只是被传递到
ugettext
进行翻译。
from django.core.mail import send_mail