Search code examples
pythondjangodjango-modelsnameerror

NameError django send_mail


Why am I getting a NameError: global name 'send_mail' is not defined?

From 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)

Thank you!

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

Solution

  • The traceback is from your views.

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

    You posted code from your models.

    classifieds/views/create.py does not have send_mail imported, I would think.

    Another question though is why are you doing this stuff on your model class and not .. in a model method ...

    EDIT: The way you put it in the question it makes it look super-weird that this send mail stuff is happening on the class and not in a method. Looking at the source, you see that it is in the Payment.complete method: https://github.com/saebyn/django-classifieds/blob/master/classifieds/models.py#L273

    send_mail is used here: https://github.com/saebyn/django-classifieds/blob/master/classifieds/views/create.py#L116

    but is not imported, import it.