当我在 django shell 中运行相同的代码时,它对我来说工作正常。但是当我启动 Python 解释器 (Python 2) 来检查一些东西时,我在尝试导入时遇到错误 - 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()
我得到的错误是
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.
非常感谢对此的任何帮助。
原文由 User 发布,翻译遵循 CC BY-SA 4.0 许可协议
Django 需要设置,以便正常运行,当您通过 manage.py shell 运行它时,manage.py 会照顾或为您设置它,但是通过 python 脚本执行它,需要手动设置。
您似乎也使用了您定义的模型,为了能够将它们导入到您的 python 脚本中,您需要将项目根文件夹的路径添加到当前 python 路径。
最后,你需要告诉 django 你的 设置文件 在哪里( 在 设置你的 django 之前),在你的 manage.py 文件中,你应该有这样的东西:
让它成为一个常量,将它命名为 \* DEFAULT_SETTINGS_MODULE *,所以你现在有:
现在您需要将常量导入脚本并告诉 django(通过设置环境变量)它应该在哪里寻找设置文件。
所以总而言之:
这样你就设置好了。