Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django exception : django.core.exceptions.ImproperlyConfigured:

Tags:

python

django

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 = "[email protected]"
            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.

like image 675
User Avatar asked Dec 01 '22 12:12

User


2 Answers

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.

like image 119
SpiXel Avatar answered Apr 27 '23 04:04

SpiXel


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.

like image 28
vramazing Avatar answered Apr 27 '23 04:04

vramazing