Django Twilio 短信 - django.core.exceptions.AppRegistryNotReady:应用程序尚未加载
Django Twilio Texting - django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
我是 Python 和 Django 的新手,但我决定基于 https://www.placecard.me/blog/django-wedding-website/. The only major difference I want to make is to change the the email communication to SMS. I came across this https://github.com/CleverProgrammer/CP-Twilio-Python-Text-App 短信应用制作我自己的婚礼网站。
我将短信应用程序合并到 Django 项目中以测试并尝试向数据库中的所有客人发送短信。我是 运行ning Python 3.6.5 和 Django 2.0.5
我的 Django 项目有以下目录结构。
我有以下代码:
settings.py
import os
enter code here`# Build paths inside the project like this:
os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'twilio',
'sms_send',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'WebsiteSMS.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
# WSGI_APPLICATION = 'wsgi.application'
WSGI_APPLICATION = 'WebsiteSMS.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-
validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME':
'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME':
'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME':
'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME':
'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
manage.py
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "WebsiteSMS.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
send_sms.py:
from twilio.rest import Client
from credentials import account_sid, auth_token, my_cell, my_twilio
client = Client(account_sid, auth_token)
my_msg = "Test message"
message = client.messages.create(to=my_cell, from_=my_twilio, body=my_msg)
我然后运行python
sms_send\send_sms.py.
这会向我的 phone 发送短信。
然后我添加以下内容以尝试向数据库中已有的两位客人发送相同的消息。我做了所有的迁移。
admin.py
from .models import SmsUser
from django.contrib import admin
class SmsUserAdmin(admin.ModelAdmin):
list_display = ('name', 'number')
search_fields = ['name', 'number']
admin.site.register(SmsUser, SmsUserAdmin)
models.py
from django.db import models
class SmsUser(models.Model):
name = models.TextField(null=True, blank=True)
number = models.CharField(max_length=13, null=True, blank=True)
def __str__(self):
return ' {}'.format(self.name)
def __str__(self):
return ' {}'.format(self.number)
并将send_sms.py改为:
from twilio.rest import Client
from credentials import account_sid, auth_token, my_cell, my_twilio
from models import SmsUser
client = Client(account_sid, auth_token)
recipients = SmsUser.objects.all()
for recipient in recipients:
client.messages.create(body='Sample text', to=recipient.number,
from_=my_twilio)
当我再次 运行 python sms_send\send_sms.py 时,出现以下错误:
PS C:\Garbage\Python\Django\WebsiteSMS> python sms_send\send_sms.py
Traceback (most recent call last):
File "sms_send\send_sms.py", line 3, in
from models import SmsUser
File "C:\Garbage\Python\Django\WebsiteSMS\sms_send\models.py", line 4, in
class SmsUser(models.Model):
File "C:\Users\Gary.HIBISCUS_PC\AppData\Local\Programs\Python\Python36-
32\lib\site-packages\django\db\models\base.py", line 100, in new
app_config = apps.get_containing_app_config(module)
File "C:\Users\Gary.HIBISCUS_PC\AppData\Local\Programs\Python\Python36-
32\lib\site-packages\django\apps\registry.py", line 244, in
get_containing_app_config
self.check_apps_ready()
File "C:\Users\Gary.HIBISCUS_PC\AppData\Local\Programs\Python\Python36-
32\lib\site-packages\django\apps\registry.py", line 127, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
我已经尝试了建议的答案,但无法正常工作。一切似乎都很好,直到我在 send_sms.py
中添加 from models import SMSUser
我希望有人能找出我的问题并指出正确的方向。
您正在尝试单独 运行 一个 python 文件,我认为这会导致您的应用失败。它正在尝试加载位于您的 django 项目中的 SmsUser
,但在使用 python <dir>/<file>.py
.
调用文件时无法访问
如果你想 运行 你的 django 项目中的这个文件并且能够作为命令访问你的模型、数据库等,你可以使用 django custom management commands
未经测试的快速示例:
# Django holds a specific management commands path like eg.:
# send_sms.management.commands.send_pending_sms_messages
# which would be as a specific path send_sms/management/commands/send_pending_sms_messages.py
from django.core.management.base import BaseCommand
from twilio.rest import Client
from credentials import account_sid, auth_token, my_cell, my_twilio
from models import SmsUser
class Command(BaseCommand):
help = 'Send pending SMS messages'
def handle(self, *args, **options):
client = Client(account_sid, auth_token)
recipients = SmsUser.objects.all()
for recipient in recipients:
client.messages.create(body='Sample text', to=recipient.number,
from_=my_twilio)
如果一切设置正确,您现在可以在您的 django 项目中使用 ./manage.py
作为命令 运行ner,例如
./manage.py send_pending_sms_messages
我是 Python 和 Django 的新手,但我决定基于 https://www.placecard.me/blog/django-wedding-website/. The only major difference I want to make is to change the the email communication to SMS. I came across this https://github.com/CleverProgrammer/CP-Twilio-Python-Text-App 短信应用制作我自己的婚礼网站。
我将短信应用程序合并到 Django 项目中以测试并尝试向数据库中的所有客人发送短信。我是 运行ning Python 3.6.5 和 Django 2.0.5
我的 Django 项目有以下目录结构。
我有以下代码:
settings.py
import os
enter code here`# Build paths inside the project like this:
os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'twilio',
'sms_send',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'WebsiteSMS.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
# WSGI_APPLICATION = 'wsgi.application'
WSGI_APPLICATION = 'WebsiteSMS.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-
validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME':
'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME':
'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME':
'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME':
'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
manage.py
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "WebsiteSMS.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
send_sms.py:
from twilio.rest import Client
from credentials import account_sid, auth_token, my_cell, my_twilio
client = Client(account_sid, auth_token)
my_msg = "Test message"
message = client.messages.create(to=my_cell, from_=my_twilio, body=my_msg)
我然后运行python sms_send\send_sms.py.
这会向我的 phone 发送短信。
然后我添加以下内容以尝试向数据库中已有的两位客人发送相同的消息。我做了所有的迁移。
admin.py
from .models import SmsUser
from django.contrib import admin
class SmsUserAdmin(admin.ModelAdmin):
list_display = ('name', 'number')
search_fields = ['name', 'number']
admin.site.register(SmsUser, SmsUserAdmin)
models.py
from django.db import models
class SmsUser(models.Model):
name = models.TextField(null=True, blank=True)
number = models.CharField(max_length=13, null=True, blank=True)
def __str__(self):
return ' {}'.format(self.name)
def __str__(self):
return ' {}'.format(self.number)
并将send_sms.py改为:
from twilio.rest import Client
from credentials import account_sid, auth_token, my_cell, my_twilio
from models import SmsUser
client = Client(account_sid, auth_token)
recipients = SmsUser.objects.all()
for recipient in recipients:
client.messages.create(body='Sample text', to=recipient.number,
from_=my_twilio)
当我再次 运行 python sms_send\send_sms.py 时,出现以下错误:
PS C:\Garbage\Python\Django\WebsiteSMS> python sms_send\send_sms.py Traceback (most recent call last): File "sms_send\send_sms.py", line 3, in from models import SmsUser File "C:\Garbage\Python\Django\WebsiteSMS\sms_send\models.py", line 4, in class SmsUser(models.Model): File "C:\Users\Gary.HIBISCUS_PC\AppData\Local\Programs\Python\Python36- 32\lib\site-packages\django\db\models\base.py", line 100, in new app_config = apps.get_containing_app_config(module) File "C:\Users\Gary.HIBISCUS_PC\AppData\Local\Programs\Python\Python36- 32\lib\site-packages\django\apps\registry.py", line 244, in get_containing_app_config self.check_apps_ready() File "C:\Users\Gary.HIBISCUS_PC\AppData\Local\Programs\Python\Python36- 32\lib\site-packages\django\apps\registry.py", line 127, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
我已经尝试了建议的答案,但无法正常工作。一切似乎都很好,直到我在 send_sms.py
中添加 from models import SMSUser我希望有人能找出我的问题并指出正确的方向。
您正在尝试单独 运行 一个 python 文件,我认为这会导致您的应用失败。它正在尝试加载位于您的 django 项目中的 SmsUser
,但在使用 python <dir>/<file>.py
.
如果你想 运行 你的 django 项目中的这个文件并且能够作为命令访问你的模型、数据库等,你可以使用 django custom management commands
未经测试的快速示例:
# Django holds a specific management commands path like eg.:
# send_sms.management.commands.send_pending_sms_messages
# which would be as a specific path send_sms/management/commands/send_pending_sms_messages.py
from django.core.management.base import BaseCommand
from twilio.rest import Client
from credentials import account_sid, auth_token, my_cell, my_twilio
from models import SmsUser
class Command(BaseCommand):
help = 'Send pending SMS messages'
def handle(self, *args, **options):
client = Client(account_sid, auth_token)
recipients = SmsUser.objects.all()
for recipient in recipients:
client.messages.create(body='Sample text', to=recipient.number,
from_=my_twilio)
如果一切设置正确,您现在可以在您的 django 项目中使用 ./manage.py
作为命令 运行ner,例如
./manage.py send_pending_sms_messages