Search code examples
pythondjangomodels

Importing models in Django python


How can I import all models in the settings.py in INSTALLED_APPS? When i`m trying to insert some model there is an error occurred: "no models named app1_model"

-ProjectName
--ProjectName
---models
----__init__.py
----admin.py
----app_1_model
----....
----app_n_model
---templates
---__init__.py
---settings.py
---urls.py
---wsgi.py
--manage.py

^ Structure of project ^


Solution

  • The INSTALLED_APPS is for apps not for models. Models are classes that live within your app, usually in /«app_name»/models.py.

    I think you have misunderstood how a Django project is structured. Try working through a tutorial example.

    a typical structure:

    /«project»/«app_name»/models.py
    

    and in settings:

    INSTALLED_APPS = [ ... '«app_name»' ... ]
    

    Your path will contain the base project directory, so you can import your app where you need it.

    And to use them:

    from «app_name».models import *
    

    Although it is always best not to import *, instead, name the classes you wish to import.

    To answer the question in the comment:

    If you don't like the idea of storing all your models in one file (even though it is normal to do this), you can create a module called models. To do this, create a directory called /«project»/«app_name»/models, inside it put __init__.py (to declare it as a module) and then create your files inside there. You then need to import your file contents into the module in __init__.py. You should read about Python modules to understand this.

    To answer the second comment question:

    To view models in admin, you should create an admin file with model admin objects.

    And finally:

    Please read through the tutorials to ensure you have a thorough understanding of Django. Otherwise you're wasting your own time!