Ayo*_*had 3 python django django-models
我是 Django 新手,我正在尝试在脚本中导入我的模型之一,就像我们在views.py 中所做的那样。我收到错误:
Traceback (most recent call last):
File "CallCenter\make_call.py", line 3, in <module>
from .models import Campaign
ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package
Run Code Online (Sandbox Code Playgroud)
我的文件结构是这样的:
我的应用\呼叫中心\
CallCenter 包含__init__.py、make_call.py、models.py、views.pyMyApp 有manage.py
Traceback (most recent call last):
File "CallCenter\make_call.py", line 3, in <module>
from .models import Campaign
ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package
Run Code Online (Sandbox Code Playgroud)
一般来说,最好将“临时”脚本 \xe2\x80\x93 任何可能从命令行手动运行的内容(例如 \xe2\x80\x93 )重构为管理命令。
\n\n这样,一旦到达您的代码,Django 运行时就会正确设置,并且您也可以免费获得命令行解析。
\n\n你make_call.py可能会变成这样:
from twilio.rest import Client\nfrom twilio.twiml.voice_response import VoiceResponse, Say, Dial, Number, VoiceResponse\nfrom CallCenter.models import Campaign\n\nfrom django.core.management import BaseCommand\n\n\ndef create_xml(campaign):\n # Creates XML\n response = VoiceResponse()\n response.say(campaign.campaign_text)\n return response\n\n\nclass Command(BaseCommand):\n def add_arguments(self, parser):\n parser.add_argument("--campaign-id", required=True, type=int)\n\n def handle(self, campaign_id, **options):\n campaign = Campaign.objects.get(pk=campaign_id)\n xml = create_xml(campaign)\n print(xml)\nRun Code Online (Sandbox Code Playgroud)\n\n它将被调用
\n\n$ python manage.py make_call --campaign-id=1\nRun Code Online (Sandbox Code Playgroud)\n\n无论你manage.py在哪里。
(记住和文件夹__init__.py中都有一个文件。)management/management/commands/