hey, I’ve just started coding with Django but I get the following error:
from pairs.models import ContractModel
ModuleNotFoundError: No module named ‘pairs’
This happens when I run the listing.py file with the python listing.py command
I searched too much but did not find the right answer.
I also checked all the paths and settings of the vs code and there are no problems.I already had several programs according to this project, which all worked correctly.
Python version: 3.11.1
Django version: 3.2.18
Pip version: Last version
from .models import ContractModel
in listing.py
show this error:
Traceback (most recent call last):
File “E:\pairing\events\pairs\listing.py”, line 1, in
from .models import ContractModel
ImportError: attempted relative import with no known parent package
Traceback (most recent call last):
File “E:\pairing\events\pairs\listing.py”, line 1, in
from pairs.models import ContractModel
ModuleNotFoundError: No module named ‘pairs’
That is a script that I wrote before and now I want to use it in this project, but I encountered an import problem at the beginning of the work.
for example:
from pairs.models import ContractModel
cd= ContractModel.objects.all()
print(cd)
If you want to run Django code, using the ORM for example, you need to initialize the Django environment before doing so. What you’re trying to do here just won’t work.
If you’re looking to run Django-related code directly from the command line, the easiest way to do it is to write a custom management command.
Sorry. I don’t want to use a custom command. I did this just for testing. I used this method in my projects before and had no problems, but now my model is not imported.
Notice: finally a celery run listing.py
Yes - because the Django environment will have been initialized by either the runserver or runserver_plus commands, or by something like the gunicorn wsgi container.
If you want to run that file directly from the command line, I already answered that question. Create it as a management command. The manage.py command initializes the Django environment before calling the designated command.