Django not in python path

DjangoTricks

Aidas Bendoraitis on development with Django, Python, and JavaScript.

2008-09-03

A Note on Python Paths

This time I decided to share some knowledge about Python paths which seemed a little bit confusing to me in the beginning of diving into Python. I am working with Django in different platforms like Mac OS X, Windows, and Linux, therefore the common patterns how to activate new python modules in all of those environments should be familiar to me.

Python modules are either *.py files or directories containing __init__.py . When defining paths to python modules, you will usually need to deal with the latter ones. A module is meant to be under python path if you can run python and import that module.

For example, if you can run the following, then django is under your python path.

Stay tuned to get deeper into python paths.

Installing modules

If a module is installable, usually all you need to do is to extract its setup directory, cd to it, and run

This will copy the module into the site-packages directory of the current python installation. It might be that you have multiple Python versions on your computer. According to django documentation, you can find the currently used site-packages by

python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"

Or you can use PEAK EasyInstall for installing python modules even faster.

Читайте также:  z-index

But sometimes you will need the latest and greatest versions of your modules directly from version control system. To make them accessible from python you should either check them out directly to site-packages (very messy and inflexible) or keep them somewhere else and do some additional magic.

Sym-linking

You can create symbolic links (symlinks) in unix-based systems like Linux or Mac OS X. A symlink is like a shortcut to a file or directory. If you create a symlink in site-packages which points to a python module which is located somewhere else, it will work as if the module was copied into site-packages.

To create a symlink, type the following in a console/terminal:

For example, if you want python to access django which is under /Library/Subversion/django_src/trunk/django , you need to write something like this (considering that your site-packages are at /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/ )

ln -s /Library/Subversion/django_src/trunk/django /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/django
rm /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/django

But as I’ve already mentioned, this works only in unix-based environments and you can’t use shortcuts in Windows for the same purpose.

*.pth files

Python supports *.pth files which contain the paths to the parent directories of your python modules one per line. Those files should be placed in site-packages and can be called whatever you want them to call. For example, you can create a file my-project.pth and write

/Library/Subversion/django_src/trunk
/Library/Subversion/myproject_src/trunk
C:\Subversion\django_src\trunk
C:\Subversion\myproject\trunk

into it. Then django and your project files will be importable in python.

However, you might have no permissions to create files under site-packages or you might need to activate different locations of python modules for different projects.

PYTHONPATH variable

The other way is to set additional paths for python just before running the externally kept modules. This is done by setting the python paths to the environment variable PYTHONPATH . Note again that python paths point not to the modules themselves, but to their parent directories!

The syntax slightly differs among different platforms.

# checking value
echo $PYTHONPATH
# setting value
export PYTHONPATH="/Library/Subversion/django_src/trunk"
# appending to the existing value
export PYTHONPATH="$PYTHONPATH;/Library/Subversion/django_src/trunk"
# checking value
echo %PYTHONPATH%
# setting value
set PYTHONPATH="C:\\Subversion\\django_src\\trunk"
# appending to the existing value
set PYTHONPATH="%PYTHONPATH%;C:\\Subversion\\django_src\\trunk"

Multiple paths can be separated by a colon («;»).

PYTHONPATH can be used in scripts and webserver configuration files, but it is not very comfortable in daily use.

Adding paths to sys.path

For the projects that you develop and which should run as standalone applications, you can set the required python paths relatively inside your python code.

Note that all python paths which you set in the PYTHONPATH variable or *.pth files as well as the path of default python libraries and the path of site-packages get listed in python variable sys.path . When you import a module, it is loaded from the first location which contains the required module. So if you have two paths to different django versions in your python paths and you import django, the django version from the first location will be used.

You can read the list of loaded python paths like this:

You can also freely modify it, for example:

>>> import sys
>>> sys.path.append("/Library/Subversion/django_src/trunk")
>>> import django

And this is an example, how to get and use paths relative to the currently loaded file:

import os, sys

SVN_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
DJANGO_PATH = os.path.join(SVN_PATH, "django_src", "trunk")
PROJECT_PATH = os.path.join(SVN_PATH, "myproject", "trunk")

sys.path += [DJANGO_PATH, PROJECT_PATH]

I hope this introduction was useful for developers and made the big picture about the paths clearer.

Some more related information can be found at the official python documentation.

Источник

Managing the Python path

pytest needs to be able to import the code in your project. Normally, when interacting with Django code, the interaction happens via manage.py , which will implicitly add that directory to the Python path.

However, when Python is started via the pytest command, some extra care is needed to have the Python path setup properly. There are two ways to handle this problem, described below.

Automatic looking for Django projects

By default, pytest-django tries to find Django projects by automatically looking for the project’s manage.py file and adding its directory to the Python path.

Looking for the manage.py file uses the same algorithm as pytest uses to find pytest.ini , tox.ini and setup.cfg : Each test root directories parents will be searched for manage.py files, and it will stop when the first file is found.

If you have a custom project setup, have none or multiple manage.py files in your project, the automatic detection may not be correct. See Managing the Python path explicitly for more details on how to configure your environment in that case.

Managing the Python path explicitly

First, disable the automatic Django project finder. Add this to pytest.ini , setup.cfg or tox.ini :

[pytest] django_find_project = false 

Next, you need to make sure that your project code is available on the Python path. There are multiple ways to achieve this:

Managing your project with virtualenv, pip and editable mode

The easiest way to have your code available on the Python path when using virtualenv and pip is to have a setup.py file and install your project in editable mode when developing.

If you don’t already have a setup.py file, creating a setup.py file with this content will get you started:

import setuptools setuptools.setup(name='myproj', version='1.0') 

This setup.py file is not sufficient to distribute your package to PyPI or more general packaging, but it should help you get started. Please refer to the Python Packaging User Guide for more information on packaging Python applications.

To install the project afterwards:

Your code should then be importable from any Python application. You can also add this directly to your project’s requirements.txt file like this:

# requirements.txt -e . django>=1.11 pytest-django 

Using pytest’s pythonpath option

You can explicitly add paths to the Python search path using pytest’s pythonpath option. This option is available since pytest 7; for older versions you can use the pytest-pythonpath plugin.

Example: project with src layout

For a Django package using the src layout, with test settings located in a tests package at the top level:

myproj ├── pytest.ini ├── src │ └── myproj │ ├── __init__.py │ └── main.py └── tests ├── testapp | ├── __init__.py | └── apps.py ├── __init__.py ├── settings.py └── test_main.py

You’ll need to specify both the top level directory and src for things to work:

[pytest] DJANGO_SETTINGS_MODULE = tests.settings pythonpath = . src 

If you don’t specify . , the settings module won’t be found and you’ll get an import error: ImportError: No module named ‘tests’ .

© Copyright 2023, Andreas Pelme and contributors. Revision 53373573 .

Источник

Ошибки Django

book24 не заставляйте меня думать

(docker) andreyolegovich.ru@server:~/HelloDjango [0] $ python3 manage.py runserver
Traceback (most recent call last):
File «manage.py», line 8, in
from django.core.management import execute_from_command_line

ModuleNotFoundError: No module named ‘django’

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File «manage.py», line 14, in
) from exc
ImportError: Couldn’t import Django. Are you sure it’s installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?

Причина в том, что в PATH не прописан путь до python. Вернитесь к шагу PATH

Disallowed host

Вы можете запустить Django с помощью

python3 manage.py runserver

И прописали в settings.py свои хосты, например так

Но при обращении к домену в браузере появляется ошибка DisallowedHost

DisallowedHost at / Invalid HTTP_HOST header: ‘www.andreyolegovich.ru’. You may need to add ‘www.andreyolegovich.ru’ to ALLOWED_HOSTS. Request Method: GET Request URL: http://www.andreyolegovich.ru/ Django Version: 2.1.5 Exception Type: DisallowedHost Exception Value: Invalid HTTP_HOST header: ‘www.andreyolegovich.ru’. You may need to add ‘www.andreyolegovich.ru’ to ALLOWED_HOSTS. Exception Location: /home/a/andreyolegovichru/.local/lib/python3.7/site-packages/django/http/request.py in get_host, line 106 Python Executable: /home/a/andreyolegovichru/.local/bin/python3.7 Python Version: 3.7.0 Python Path: [‘/home/a/andreyolegovichru/andreyolegovich.ru/public_html/HelloDjango’, ‘/home/a/andreyolegovichru/.local/lib/python3.7/site-packages’, ‘/home/a/andreyolegovichru/andreyolegovich.ru’, ‘/opt/passenger40/helper-scripts’, ‘/home/a/andreyolegovichru/.local/lib/python37.zip’, ‘/home/a/andreyolegovichru/.local/lib/python3.7’, ‘/home/a/andreyolegovichru/.local/lib/python3.7/lib-dynload’, ‘/home/a/andreyolegovichru/.local/lib/python3.7/site-packages’] Server time: Sun, 3 Feb 2019 20:07:57 +0000

Проверьте, всё ли правильно прописали в settings.py ALLOWED_HOSTS.

Выключите Django, закройте все консоли подключенные к хостингу или все консоли на локальной машине.

Очистите кэш браузера или откройте url другим браузером.

Не работает runserver Django

Если Вы выполняете команду

python3 manage.py runserver

И ничего не происходит, или например, у Вас работал самый первый проект, а запустить второй не получается — скорее всего дело в хостинге. На нём может быть закрыта возможность слушать порты и выбор рабочего проекта происходит с помощью какого-то скрипта.

Если Вы, как и я, пользуетесь хостингом beget , тот этот скипт будет называться passenger_wsgi.py и лежать будет на одном уровне с директорией public_html.

Web application could not be started

Если Вы хотите переключиться между проектами и уже обновили скрипе passenger_wsgi.py но получили ошибку

Web application could not be started

Скорее всего Вы забыли пересоздать файл tmp/restart.txt

(docker) andreyolegovich@server:~/andreyolegovich.ru [0] $ touch tmp/restart.txt

Также советую перепроверить не забыли ли Вы поменть системный путь на нужный Вам проект.

При смене проекта обычно нужно делать два изменения в файле passenger_wsgi.py

# -*- coding: utf-8 -*-
import os, sys
sys.path.insert(0, ‘/home/a/andreyolegovich/andreyolegovich.ru/public_html/Project_1’)
#sys.path.insert(0, ‘/home/a/andreyolegovich/andreyolegovich.ru/public_html/Project_2’)
sys.path.insert(1, ‘/home/a/andreyolegovich/.local/lib/python3.7/site-packages’)
os.environ[‘DJANGO_SETTINGS_MODULE’] = ‘Project_1.settings’
#os.environ[‘DJANGO_SETTINGS_MODULE’] = ‘Project_2.settings’
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

Ещё одна возможная причина — незаданные переменные в файле manage.py

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run ‘python manage.py migrate’ to apply them.

ERROR: Can not perform a ‘—user’ install. User site-packages are not visible in this virtualenv.

Если вы пользуетесь виртуальным окружением флаг —user вам скорее всего вообще не нужен.

  • Поиск по сайту
  • aofeed — Telegram канал чтобы следить за выходом новых статей
  • aofeedchat — задать вопрос в Телеграм-группе

Источник

Оцените статью