5

When i run the same code in django shell it works fine for me. but when I fire up the Python interpreter (Python 2) to check some things, I get the an error when I try importing - from django.contrib.auth.models import User

import os
import django
django.setup()
import smtplib
import sys
sys.path.insert(0, "/edx/app/edxapp/edx-platform/lms/djangoapps/courseware")
import dateutil.relativedelta

from django.conf import settings
from django.contrib.auth.models import User
from opaque_keys.edx.keys import CourseKey
from courseware.models import StudentModule

from datetime import datetime



def PCSurvey_email():
    for student in StudentModule.objects.filter(module_type="PCSurvey"):
        two_months_date =  datetime.now().date() - dateutil.relativedelta.relativedelta(months=2)
        created = student.created.date()
        if created == two_months_date :
            user_id = student.student_id
            user_email = User.objects.get(id = user_id).email
            FROM = "user@example.com"
            TO = [user_email] # must be a list
            SUBJECT = "Hello!"
            TEXT = "This message was sent with Python's smtplib."
                        # Prepare actual message

            message = """\
            From: %s
            To: %s
            Subject: %s
            %s
            """ % (FROM, ", ".join(TO), SUBJECT, TEXT)

                # Send the mail

            server = smtplib.SMTP('outlook.net')
            server.sendmail(FROM, TO, message)
            server.quit()

     #deleting the module
            smod = StudentModule.objects.get(module_type="PCSurvey", course_id = student.course_id, student_id= student.student_id)
            smod.delete()

The error that I get is

    Traceback (most recent call last):
  File "/edx/app/edxapp/edx-platform/lms/djangoapps/courseware/PCSurvey_email.py", line 4, in <module>
    django.setup()
  File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 22, in setup
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
  File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 53, in __getattr__
    self._setup(name)
  File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 39, in _setup
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

Any help on this is very much appreciated.

User
  • 85
  • 1
  • 2
  • 8
  • Does this answer your question? [ImproperlyConfigured: You must either define the environment variable DJANGO\_SETTINGS\_MODULE or call settings.configure() before accessing settings](https://stackoverflow.com/questions/26082128/improperlyconfigured-you-must-either-define-the-environment-variable-django-set) – Stephen C Jul 30 '22 at 04:24

4 Answers4

18

Django needs to be setup, in order to run fine, when you run it through manage.py shell, manage.py takes care or setting it up for you, but doing it via a python script, needs manual setup.

You also seem to have used your defined models, to be able to import them into your python script, you need to add the path to the root folder of your project to the current python path.

Finally, you need to tell django where your settings file is (before setting up your django), in your manage.py file, you should have something like this :

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")

Go make it a constant, name it * DEFAULT_SETTINGS_MODULE *, so you now have:

os.environ.setdefault("DJANGO_SETTINGS_MODULE", DEFAULT_SETTINGS_MODULE)

Now you need to import the constant into your script and tell django (By setting an env var) where it should look for the settings file.

So in all:

import sys, os
sys.path.insert(0, "/path/to/parent/of/courseware") # /home/projects/my-djproj

from manage import DEFAULT_SETTINGS_MODULE
os.environ.setdefault("DJANGO_SETTINGS_MODULE", DEFAULT_SETTINGS_MODULE)

import django
django.setup() 

This way you're setup up just fine.

SpiXel
  • 4,338
  • 1
  • 29
  • 45
  • but where should i need to put all that code? new file ? what folder ? – Nestor Colt Dec 04 '17 at 10:48
  • 2
    @NestorColt In a shell that you run, or in your manage.py, or any script that's being run like "python script", not "python manage.py script". – SpiXel Dec 05 '17 at 05:47
3

For new users coming on this question. If you don't want to setup django settings file manually as described wonderfully by @SpiXel You can run python manage.py shell from the project directory which will basically link the settings file that django needs automatically.

vramazing
  • 94
  • 1
  • 1
  • 6
2

When you open a shell, django automatically sets itself up.

With Python interpreter you have to do this manually:

import django
django.setup()
Jahongir Rahmonov
  • 13,083
  • 10
  • 47
  • 91
0

Just a simple solution all can try!

I tried to run my custom script inside shell only by using the following way:

python manage.py shell < /path_to_script
Mayur Gupta
  • 303
  • 2
  • 14