Search code examples
pythondjangotelegrampython-telegram-bot

Use django models in an external .py file


I am trying to make a telegram bot that needs access to a database of a django app.

I want to avoid making webservices in views.py to manage content because I don't want to make an API and just want to keep things separated by the moment, so I need to access to the django ORM in the telegram bot.

I have imported the models in my bot main file but I get this message:

File "C:\Python37-32\lib\site-packages\django\apps\registry.py", line 135, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

Once I get this message, I add the app to settings adding this line to the INSTALLED_APPS variable: 'localadmin.apps.BotConfig' and the next lines in the apps.py file:

class BotConfig(AppConfig):
    name = 'localadmin.bot'

Having in mind that there's a folder called "bot" which have the main.py file that launches the bot. So, I think, everything was in order, but, with this changes, I get the next error message.

File "C:\Python37-32\lib\site-packages\django\apps\registry.py", line 135, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

So I guess my problem, is that I need to use a proper django app to use the models, but I can't do this, due that my app is a main telegram bot wrapper.

Another option I have tried is to put the main wrapper telegram bot code on the views.py of my app, and then, when the django server is launched, launch the telegram bot function on a separate thread, but telegram signal returns an error telling me that it could only be ran on the main thread...

So by the moment I ran out of ideas...


Solution

  • As documentation states

    If you’re using components of Django “standalone” – for example, writing a Python script which loads some Django templates and renders them, or uses the ORM to fetch some data – there’s one more step you’ll need in addition to configuring settings.

    After you’ve either set DJANGO_SETTINGS_MODULE or called configure(), you’ll need to call django.setup() to load your settings and populate Django’s application registry