Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django Twilio短信-Django.core.exceptions.AppRegistryNotReady:应用程序不可用';还没装呢_Python_Django_Python 3.x_Django 2.0 - Fatal编程技术网

Python Django Twilio短信-Django.core.exceptions.AppRegistryNotReady:应用程序不可用';还没装呢

Python Django Twilio短信-Django.core.exceptions.AppRegistryNotReady:应用程序不可用';还没装呢,python,django,python-3.x,django-2.0,Python,Django,Python 3.x,Django 2.0,我对Python和Django还不熟悉,但已经决定基于它创建自己的婚礼网站。我想做的唯一主要区别是将电子邮件通信改为短信。我偶然发现了这个短信应用程序 我将短信应用程序合并到Django项目中,以测试并尝试向数据库中的所有来宾发送短信。我正在运行Python 3.6.5和Django 2.0.5 我的Django项目有以下目录结构 我有以下代码: 设置.py import os enter code here`# Build paths inside the project like thi

我对Python和Django还不熟悉,但已经决定基于它创建自己的婚礼网站。我想做的唯一主要区别是将电子邮件通信改为短信。我偶然发现了这个短信应用程序

我将短信应用程序合并到Django项目中,以测试并尝试向数据库中的所有来宾发送短信。我正在运行Python 3.6.5和Django 2.0.5

我的Django项目有以下目录结构

我有以下代码:

设置.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/'
#!/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)
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)
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)
管理.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/'
#!/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)
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)
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

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\u send\send\u sms.py

这会向我的手机发送短信

然后,我添加以下内容,尝试向数据库中已经存在的两位来宾发送相同的消息。我做了所有的迁移

admin.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/'
#!/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)
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)
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)
型号.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/'
#!/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)
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)
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)
当我再次运行pythonsms\u send\send\u sms.py时,我得到以下错误:

PS C:\Garbage\Python\Django\WebsiteSMS>pythonsms\u send\send\u sms.py 回溯(最近一次呼叫最后一次): 文件“sms\u send\send\u sms.py”,第3行,在 从模型导入SmsUser 文件“C:\Garbage\Python\Django\WebsiteSMS\sms\u send\models.py”,第4行,在 SmsUser类(models.Model): 文件“C:\Users\Gary.HIBISCUS\u PC\AppData\Local\Programs\Python\Python36- 32\lib\site packages\django\db\models\base.py“,第100行,在新建 app\u config=apps.get\u包含app\u config(模块) 文件“C:\Users\Gary.HIBISCUS\u PC\AppData\Local\Programs\Python\Python36- 32\lib\site packages\django\apps\registry.py”,第244行,在 获取包含应用程序配置的应用程序 self.check_apps_ready() 文件“C:\Users\Gary.HIBISCUS\u PC\AppData\Local\Programs\Python\Python36- 32\lib\site packages\django\apps\registry.py”,第127行,在check\u apps\u ready中 raise AppRegistryNotReady(“应用程序尚未加载。”) django.core.exceptions.AppRegistryNotReady:尚未加载应用程序

我尝试了建议的答案,但未能使其起作用。在我在send_sms.py中添加从模型导入的SMSUser之前,一切似乎都很好


我希望有人能发现我的问题,并为我指出正确的方向。

您试图单独运行python文件,我认为这会导致您的应用程序失败。它正在尝试加载django项目中的
SmsUser
,但在使用
python/.py
调用文件时无法访问该文件

如果您希望在django项目中运行此文件,并能够作为命令访问模型、数据库等,则可以使用

快速未经测试的示例:

# 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
作为命令运行程序,如


/manage.py发送待处理的短信

感谢@Nrzonline的详细解释。这清除了我的错误消息,但没有消息发送,我将不得不检查我的代码。