4

I'm trying to understand how to configure Pylance to make it work correctly in my Django project.

Below is one of many examples where Pylance is not able to find what I'm looking for. Here, I obviously need models from django.db. But there are only theses 6 suggestions below...

​

Here is what I know or tried:

  • My interpreter is correctly selected (Python 3.10.4)
  • Pylance seems to work perfectly with Python (not Django) related stuff.
  • I'm using Poetry as a package manager, and no virtual env because I work in a self-contained dev container. There is only one python installed on it.
  • In my VS Code config (using devcontainer.json) :"python.analysis.extraPaths": ["${workspaceFolder}/dj_proj/dj_apps"] -> which works to prevent missing imports. I have no false warnings about missing imports, just the inability to see the right suggestions in intellisense.
  • I cleaned __pycache__ and .pyc files -> no effect
  • I ensured there is a __init__.py pretty much everywhere
  • my sys.path (PYTHONPATH) looks like this (where dj_proj is my django project and dj_apps my apps folder):

['/workspace/dj_proj/dj_apps',
 '/workspace/dj_proj',
 '/usr/local/lib/python310.zip',
 '/usr/local/lib/python3.10',
 '/usr/local/lib/python3.10/lib-dynload',
 '',
 '/usr/local/lib/python3.10/site-packages']

I'm suspecting this PYTHONPATH variable to be messy or not sorted the right way, but I'm not sure.

Any idea on what could be wrong? Thanks!

David Dahan
  • 10,576
  • 11
  • 64
  • 137
  • Did you `from django.forms import models` instead of `from django.db import models`? – aaron May 01 '22 at 13:57
  • 1
    It's not a typo, I have this issue with pretty much everything in Django. Right now I'm writing `class HomeView(TemplateView)` and Pylance will never be able to import TemplateView from `django.views.generic` by itself. – David Dahan May 02 '22 at 07:37
  • This issue on Github is still open. I think there is no way to solve this problem at present. Here is the link:https://github.com/microsoft/pylance-release/issues/1931 – MingJie-MSFT May 03 '22 at 01:31
  • I've got the same issue, any news ? – Alexandre Savinien Oct 06 '22 at 21:57

2 Answers2

2

For performance reasons, you must use the following settings for autocomplete.

"python.analysis.packageIndexDepths": [
    {
        "name": "django",
        "depth": 5
    }
]

Similar settings should be used for each external library (the appropriate depth level must be set because the default is 1)

enter image description here

miru87
  • 456
  • 1
  • 3
  • 13
0

I believe you should install the Django extension in VS Code. Even though some obvious stuff gets always overseen by the language support, at least that extension contains some useful stuff like pre-made models, CBVs and widely-used imports such as these:

enter image description here

I hope this is useful to you.

Victor Donoso
  • 411
  • 2
  • 9