Django Twilio Texting - django.core.exceptions.AppRegistryNotReady:尚未加载应用

时间:2018-05-10 13:06:07

标签: python django python-3.x django-2.0

我是Python和Django的新手,但已决定根据https://www.placecard.me/blog/django-wedding-website/创建自己的婚礼网站。我想要做的唯一主要区别是将电子邮件通信更改为SMS。我遇到了这个https://github.com/CleverProgrammer/CP-Twilio-Python-Text-App短信应用。

我将短信应用程序合并到一个Django项目中,以测试并尝试向数据库中的所有访客发送文本消息。我正在运行Python 3.6.5和Django 2.0.5

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

Picture 1

我有以下代码:

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。

这会向我的手机发送短信。

然后我添加以下内容以尝试向数据库中已有的两个guest虚拟机发送相同的消息。我做了所有的迁移。

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(最近一次调用最后一次):         文件“sms_send \ send_sms.py”,第3行,in           从模型导入SmsUser         文件“C:\ Garbage \ Python \ Django \ WebsiteSMS \ sms_send \ models.py”,第4行,                  class SmsUser(models.Model):         文件“C:\ Users \ Gary.HIBISCUS_PC \ AppData \ Local \ Programs \ Python \ Python36-       32 \ lib \ site-packages \ django \ db \ models \ base.py“,第100行, new           app_config = apps.get_containing_app_config(模块)         文件“C:\ Users \ Gary.HIBISCUS_PC \ AppData \ Local \ Programs \ Python \ Python36-       32 \ lib \ site-packages \ django \ apps \ registry.py“,第244行,in       get_containing_app_config           self.check_apps_ready()         文件“C:\ Users \ Gary.HIBISCUS_PC \ AppData \ Local \ Programs \ Python \ Python36-       在check_apps_ready中的32 \ lib \ site-packages \ django \ apps \ registry.py“,第127行           提升AppRegistryNotReady(“尚未加载应用程序。”)       django.core.exceptions.AppRegistryNotReady:尚未加载应用。

我已尝试过建议的答案,但未能使其正常工作。在我从send_sms.py

中的模型导入SMSUser添加之前,一切似乎都很好

我希望有人能够找出我的问题并指出我正确的方向。

1 个答案:

答案 0 :(得分:1)

您正在尝试单独运行一个python文件,我认为这会导致您的应用失败。它正在尝试加载位于您的django项目中的 string query = "INSERT INTO test (capacity) VALUES (@capacity)"; MySqlCommand = new MySqlCommand(query, MySqlConnection); MySqlCommand.Parameters.AddWithValue("@capacity", 80.018); MySqlCommand.ExecuteNonQuery(); ,但在使用SmsUser调用该文件时无法访问。

如果要在django项目中运行此文件并能够作为命令访问模型,数据库等,可以使用django custom management commands

快速未经测试的例子:

python <dir>/<file>.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) 作为命令运行器,如

./manage.py