pythondjangosublimetext

Django is not importing models: Sublime text can't find django. Windows 11


I've been working through Python Crash Course e2, and got stuck on Ch.18.

Having opened models.py, and entered the code, the error message is:

ModuleNotFoundError: No module named 'django'

I have spent some time working on this, without a solution.

Could it be that PCCe2 is out of date, or is there a workaround solution?

ChatGPT has said to make sure to activate the virtual environment, make sure Django is installed; verify the installation; check my Python environment and ensure it is activated; check for multiple Python installations; check the installation path; verify the installation path; check that "models.py" is in the app directory, and the app is listed in the installed apps, etc.

I have tried all of these, and the text editor cannot seem to find the module django. But it is among the files.

Here is the settings, with INSTALLED APPS list:

from pathlib import Path

INSTALLED_APPS = [
    # My apps
    'learning_logs',
    # Default django apps
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

This is the line where I get the error:

from django.db import models

Unfortunately, I'm not so sure what is meant by "Related model", hence it's omission.

I will say that in terminal, and error message I got was: ModuleNotFoundError: No module named 'django.utils'.

I hope that makes sense.


Solution

  • You can create a Build System for your project where you can specify a python environment to use:

    {
        "cmd": ["/full/path/to/your/specific/python", "$file"],
        "selector": "source.python",
        "file_regex": "^\\s*File \"(...*?)\", line ([0-9]*)"
    }
    

    Generally though, you don't need to run any files when working with Django. Just run python manage.py runserver (in a terminal), edit the source files and the app will be reloaded automatically; refresh the browser to see the results.

    If you do need to run a standalone script that uses Django, make sure to add django.setup():

    import django
    django.setup()
    
    # now you can use models and other Django features