Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the DJANGO_SETTINGS_MODULE env variable?

I'm trying to fix a bug I'm seeing in a django application where it isn't sending mail. Please note that the application works great, it's only the mail function that is failing. I've tried to collect error logs, but I can't come up with any errors related to sending the mail. So, I made a example to try and force the errors. Here is the example:

from django.core.mail import send_mail

send_mail('hi', 'hi', '[email protected]', ['[email protected]'], fail_silently=False)

When I run the above code, I get the following error:

Traceback (most recent call last):
  File "dmail.py", line 14, in <module>
    send_mail('hi', 'hi', '[email protected]', ['[email protected]'], fail_silently=False)
  File "/data/servers/calendar_1/lib/python2.7/site-packages/django/core/mail/__init__.py", line 59, in send_mail
    fail_silently=fail_silently)
  File "/data/servers/calendar_1/lib/python2.7/site-packages/django/core/mail/__init__.py", line 29, in get_connection
    path = backend or settings.EMAIL_BACKEND
  File "/data/servers/calendar_1/lib/python2.7/site-packages/django/utils/functional.py", line 184, in inner
    self._setup()
  File "/data/servers/calendar_1/lib/python2.7/site-packages/django/conf/__init__.py", line 39, in _setup
    raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.

I managed to fix my test example by changing the code to this:

from django.core.mail import send_mail

from django.conf import settings
settings.configure(TEMPLATE_DIRS=('/path_to_project',), DEBUG=False, TEMPLATE_DEBUG=False)

send_mail('hi', 'hi', '[email protected]', ['[email protected]'], fail_silently=False)

However, when I try to add those settings to send_mail.py, I'm still not getting any mail from my actual application. Can someone explain to me, clearly, how I setup the DJANGO_SETTINGS_MODULE so that both my example and my application can see it? Failing that, can someone tell me how to setup meaningful logging in django so I actually see mail related errors in the logs? Any tips or guidance would be greatly appreciated.

like image 702
Matthew Avatar asked Sep 14 '25 04:09

Matthew


1 Answers

Do not set it from outside the application. Make a entry for DJANGO_SETTINGS_MODULE variable within your wsgi file. Everytime your server will be started, this variable will be set automatically.

For example:

import os
os.environ['DJANGO_SETTINGS_MODULE'] = '<project_name>.settings'
like image 193
Moinuddin Quadri Avatar answered Sep 15 '25 18:09

Moinuddin Quadri