1

I'm brand new to Django and Python, and not sure how to get around this problem, but I know what's wrong and why...

I'm connecting to a MQTT broker (internet of things messaging protocol / provider) so I can update a webpage with data from some sensors I have.

I've started the MQTT service in my init as was suggested below, but I don't know enough to know if that's right or wrong, but it works.

https://stackoverflow.com/a/41017210/2408033

My problem happens, when I want to try to update my database with the messages I receive from the MQTT broker. I need to import my model so I can update it, but the model hasn't been loaded yet, and it throws the error - "Apps aren't loaded yet."

I was reading that you shouldn't attempt to import models before the Django setup has run (which is after init) so I'm not sure where / how to start the loop for the MQTT broker thread?

Where else can I place the code to start the loop where it won't be triggered a second time?

Ben987654
  • 3,280
  • 4
  • 27
  • 50

1 Answers1

0

You can put it in the ready function of apps.py of your project. For example, in my foo app, I will have the following setup:

# code in __init__.py
default_app_config = 'foo.apps.MyFooConfig'

# code in apps.py
from django.apps import AppConfig

class MyFooConfig(AppConfig):
    name = 'Foo'

    def ready(self):
        from chat.mqtt import client
        client.loop_start()

More information can be read up here. Basically, this is introduced on Django 1.7 onwards.

Zac Kwan
  • 5,587
  • 4
  • 20
  • 27