skip to Main Content

I’m using Django-REST framework with a telegram-bot in here. I need to import models from Django inside my telegram-bot file. I’m getting module not found error and probably thinking something wrong. Telegram-bot file is commands.py and the django models is models.py. The whole project looks like this:

Project directories

I just want to properly import models inside my commands.py file

2

Answers


  1. Here is the possible solution for your question..
    add following code inside my commands.py file

    import sys
    from django.apps import apps
    
    from django.conf import settings
    
    settings.configure(INSTALLED_APPS=['app_name'])
    
    apps.populate(settings.INSTALLED_APPS)
    
    from app_name.models import YourModel
    

    also you may need to update path.

    import sys
    sys.path.append('path/to/your/django/project')
    
    Login or Signup to reply.
  2. As you mentioned, You are using Django REST Framework, so you should try with a serializer file. import your model in serializer file, because the syntax is correct ‘from app_name.models import YourModel’. Moreover, instead of settings.configure(INSTALLED_APPS=[‘app_name’]) try this in settings.py
    file in INSTALLED_APPS = ‘app_name.apps.AppNameConfig’.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search