django调用py报错 django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE...

本文介绍了解决Django中因环境变量DJANGO_SETTINGS_MODULE未设置而导致的ImproperlyConfigured异常的方法。通过在user_enterpoint.py文件的主函数中设置环境变量并避免提前导入models模块,确保了Django项目的正确初始化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

完整报错信息如下

django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

 

 

经查询由于user_enterpoint.py文件和manage.py文件在同级目录下,因此在main方法里面要加入如下代码,并且在开头import那里不能导入models模块

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "crazyeyes.settings")
    import django
    django.setup()



import getpass,os
#from audit import models #models模块不能再此处import
from django.contrib.auth import authenticate
 

 

完整代码如下所示



import getpass,os
from django.contrib.auth import authenticate

class UserPortal(object):
"""用户命令行端交互入口"""
def __init__(self):
pass

def user_auth(self):
"""完成用户交互"""
retry_count=0
while retry_count<3:
username=input("Username").strip()
if len(username) == 0: continue
password=getpass.getpass("Password:").strip()
print("Password can not be null")
user=authenticate(username=username,password=password)
if user:
self.user=user
print("welcome login... ")
retry_count+=1
else:
exit("Too many attempts.")



def interactive(self):
"""交互函数"""
self.user_auth()



if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "crazyeyes.settings")
import django
django.setup()
from audit import models

portal=UserPortal()
portal.interactive()

 

 

 再次执行user_enterpoint.py, 不在报错

 

转载于:https://www.cnblogs.com/qinhan/p/8309961.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值