0
votes

I’m new to Python and Django, but have decided to make my own wedding website based on 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 texting app.

I incorporated the texting app into a Django project to test and attempt to send a text message to all guests in the database. I’m running Python 3.6.5 and Django 2.0.5

I have the following directory structure for my Django project.

Picture 1

I have the following code:

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)

I then run python sms_send\send_sms.py.

This sends a SMS to my phone.

I then add the following to try and send the same message to both guests already in the database. I did all the migrations.

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)

And change send_sms.py to the following:

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)

When I run python sms_send\send_sms.py again I get the following error:

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.

I’ve tried the suggested answers but have not been able to get this working. Everything seems fine until I add from models import SMSUser in send_sms.py

I hope someone can identify my problem and point me in the right direction.

1

1 Answers

1
votes

You are attempting to run a python file individually which I think causes your app to fail. It is attempting to load SmsUser which lives within your django project, but can not be reached when calling the file with python <dir>/<file>.py.

If you want to run this file within your django project and being able to access your models, database, etc as a command, you could use django custom management commands

Quick untested example:

# 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)

If all set up properly, you can now use the ./manage.py as your command runner within your django project like

./manage.py send_pending_sms_messages