When use Pants to build Django it raise "ModuleNotFoundError: No module named"

Question:

I configured Pantsbuild for our Django project, and everything worked neatly. Here is my BUILD file:

python_requirement(
    name="django",
    requirements=["django==4.1.1"],
)


python_sources(
    name="lib",
    dependencies=[
        ":django",
        "//src/jango/jango",
    ],
)

pex_binary(
    name="manage",
    entry_point="manage.py",
    restartable=True,
)

but when I added django-filter, and run the code with the following command:

./pants run src/jango:manage -- runserver

I faced an error:

Traceback (most recent call last):
    File "/usr/lib/python3.10/runpy.py", line 196, in _run_module_as_main
    return _run_code(code, main_globals, None,
    File "/usr/lib/python3.10/runpy.py", line 86, in _run_code
    exec(code, run_globals)
    File "/home/xurvan/monorepo/src/jango/manage.py", line 8, in <module>
    import django_filters
ModuleNotFoundError: No module named 'django_filters'

I also installed Django Rest Framework, and it works fine. But I have the same problem with django-cors-headers. I don’t understand the difference.

Asked By: Xurvan

||

Answers:

If React Front-end and Backend as DRF use this snippet.

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",
]

I could not understand the reason behind strange behavior, but all we need to do is to disable Django autoreloader. As official Pantsbuild group wrote in their Github:

with runserver we turn off Django’s autoreloader, since we rely on Pants’s own file-watching instead, by setting restartable=True on the pex_binary targets for manage.py

So running code with the following command solved my problem:

./pants run src/jango:manage -- runserver --noreload
Answered By: Xurvan
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.