Wsgi error no module named django

Hi, I am still not able to resolve this with django rest framework and centos 7 and python 3.6 .This is my django.conf WSGIScriptAlias / /venv/core/core/wsgi.py WSGIPythonHome /venv WSGIPythonPath ...

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Comments

@akshayk10128

Hi, I am still not able to resolve this with django rest framework and centos 7 and python 3.6 .This is my django.conf

WSGIScriptAlias / /venv/core/core/wsgi.py
WSGIPythonHome /venv
WSGIPythonPath /venv/core/core

<Directory /venv/core/core>
    <Files wsgi.py>
        Require all granted
    </Files>
</Directory>

WSGIDaemonProcess core python-path=/venv/core/core/ python-home=/venv
WSGIProcessGroup core

@akshayk10128

This is my wsgi.py file in django project repo :

import os,sys

exec(open("/venv/bin/activate_this.py").read(), {'__file__': "/venv/bin/activate_this.py"})

sys.path.append('/venv/core/core')

sys.path.append('/venv/lib/python3.6/site-packages')

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ipan_core.settings")

application = get_wsgi_application()

@akshayk10128

Error log files : 
[mpm_prefork:notice] [pid 22418] AH00163: Apache/2.4.6 (CentOS) mod_wsgi/4.6.4 Python/3.6 configured -- resuming normal operations
[Wed May 02 10:31:34.054712 2018] [core:notice] [pid 22418] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND'
[Wed May 02 10:31:36.514895 2018] [wsgi:error] [pid 22419] [remote 125.63.68.155:27751] mod_wsgi (pid=22419): Failed to exec Python script file ''.
[Wed May 02 10:31:36.514941 2018] [wsgi:error] [pid 22419] [remote 125.63.68.155:27751] mod_wsgi (pid=22419): Exception occurred processing WSGI script '
[Wed May 02 10:31:36.515136 2018] [wsgi:error] [pid 22419] [remote 125.63.68.155:27751] Traceback (most recent call last):
[Wed May 02 10:31:36.515159 2018] [wsgi:error] [pid 22419] [remote 125.63.68.155:27751]   File "", line 37, in <module>
[Wed May 02 10:31:36.515181 2018] [wsgi:error] [pid 22419] [remote 125.63.68.155:27751]     from django.core.wsgi import get_wsgi_application
[Wed May 02 10:31:36.515215 2018] [wsgi:error] [pid 22419] [remote 125.63.68.155:27751] ModuleNotFoundError: No module named 'django'

@GrahamDumpleton

When you activate the Python virtual environment from the command line and run python, what do you get when you enter:

import sys
print(sys.prefix)

Please don’t modify the paths you give me. You appear to have done that in the configuration snippets you gave me as they don’t match what the log is showing for the WSGI script file path. It makes it impossible to validate whether you are using the correct paths.

Also, what do you get for:

import django
print(django.__file__)

@akshayk10128

Python 3.6.4 (default, Dec 19 2017, 14:48:12)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print(sys.prefix)
/ipan_env
>>> import django
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'django'
>>> print(django.__file__)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'django' is not defined
>>>

@GrahamDumpleton

Which says that Django hasn’t even been installed in the virtual environment. Once you have it installed, then you should use /ipan_env as the value for WSGIPythonHome and python-home.

@akshayk10128

But when i use sudo from command line , django gets imorted. Is it a permission issue?

@akshayk10128

My Project run fine when i use sudo python3.6 manage.py runserver but gives import error without using sudo.

@GrahamDumpleton

Do not create your virtual environment as root using sudo. Also do not install packages into it as root using sudo. The user that Apache runs your code as will not be able to access stuff if root applies restrictive permissions. Is also a bad idea to install stuff directly under / directory.

Create a directory something like /var/www/project. Change the ownership to you. Put in that directory the virtual environment and your project code with everything owned by you. Directories and files need to be accessible to other users so that the Apache user can access it. Install packages into the virtual environment as you. Set up mod_wsgi to use your project from that location.

Always run python manage.py runserver during development as you, never as root.

@akshayk10128

After giving proper permissions its fixed and working.
Thanks man!

@lenheard

I have to apologies… but I just cant get this right… I am probably reading over the correct answer
I went through many… many.. google articles and this one seems to be the closest to my problem. Please … if you can help me

my apache2 sites-available lenwsgi.conf

lenwsgi.conf.txt

now my wsgi.py path = /home/kallie/ftp/files/AI

wsgi .txt

the apache2 error log

apache2_error_log.txt

my file structure
image

my python ( main environment )
image

python virtual environment (env)
image

django stuff
image

Thank you in advance
Len

@GrahamDumpleton

@ghost

@piterkey

uwsgi —python-version
maybe you mean
uwsgi —version

@lahirusamaraweera

After giving proper permissions its fixed and working.
Thanks man!

What was the permission you give?

Настраиваю новый сервак вот конфиги
uwsgi+supervisor+nginx

[uwsgi]
virtualenv = /home/nameuser/srisovki/venv_srisovki
home = /home/nameuser/srisovki/venv_srisovki
chdir = /home/nameuser/srisovki/srisovki
uid = nameuser
gid = nameuser
env = LANG=ru_RU.UTF-8
env = DJANGO_SETTINGS_MODULE=vsesrisovki.settings.prod
module = vsesrisovki.wsgi:application
plugins = python3
master = true
chmod-socket = 666
socket = /home/nameuser/srisovki/configs/srisovki.sock
wsgi-file = /home/nameuser/srisovki/srisovki/vsesrisovki/wsgi.py
processes = 9
threads = 2
enable-threads = true
vacuum = true
touch-reload = /home/nameuser/srisovki/configs/touch

[program:srisovki]
user = nameuser
group = nameuser
directory = /home/nameuser/srisovki/srisovki
command = /usr/local/bin/uwsgi --ini /home/nameuser/srisovki/configs/uwsgi.ini
autostart = true
autorestart = true
stderr_logfile = /var/log/supervisor/srisovki_err.log
stdout_logfile = /var/log/supervisor/srisovki_out.log
stopsignal = QUIT

Ошибка

[uWSGI] getting INI configuration from /home/nameuser/srisovki/configs/uwsgi.ini
*** Starting uWSGI 2.0.18 (64bit) on [Sun Apr  5 15:00:02 2020] ***
compiled with version: 7.5.0 on 05 April 2020 07:35:08
os: Linux-4.15.0-91-generic #92-Ubuntu SMP Fri Feb 28 11:09:48 UTC 2020
nodename: s5
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 4
current working directory: /home/nameuser/srisovki/srisovki
detected binary path: /usr/local/bin/uwsgi
chdir() to /home/nameuser/srisovki/srisovki
your processes number limit is 30769
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uwsgi socket 0 bound to UNIX address /home/nameuser/srisovki/configs/srisovki.sock fd 3
Python version: 3.6.9 (default, Nov  7 2019, 10:44:02)  [GCC 8.3.0]
PEP 405 virtualenv detected: /home/nameuser/srisovki/venv_srisovki
Set PythonHome to /home/nameuser/srisovki/venv_srisovki
Python main interpreter initialized at 0x56337e9bbfa0
python threads support enabled
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 833760 bytes (814 KB) for 18 cores
*** Operational MODE: preforking+threaded ***
Traceback (most recent call last):
  File "./vsesrisovki/wsgi.py", line 12, in <module>
    from django.core.wsgi import get_wsgi_application
ModuleNotFoundError: No module named 'django'
unable to load app 0 (mountpoint='') (callable not found or import error)
Traceback (most recent call last):
  File "/home/nameuser/srisovki/srisovki/vsesrisovki/wsgi.py", line 12, in <module>
    from django.core.wsgi import get_wsgi_application
ModuleNotFoundError: No module named 'django'
unable to load app 0 (mountpoint='') (callable not found or import error)
*** no app loaded. going in full dynamic mode ***
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 16440)
spawned uWSGI worker 1 (pid: 16441, cores: 2)
spawned uWSGI worker 2 (pid: 16442, cores: 2)
spawned uWSGI worker 3 (pid: 16443, cores: 2)
spawned uWSGI worker 4 (pid: 16444, cores: 2)
spawned uWSGI worker 5 (pid: 16445, cores: 2)
spawned uWSGI worker 6 (pid: 16446, cores: 2)
spawned uWSGI worker 7 (pid: 16447, cores: 2)
spawned uWSGI worker 8 (pid: 16448, cores: 2)
spawned uWSGI worker 9 (pid: 16449, cores: 2)
unable to stat() /home/nameuser/srisovki/configs/touch, events will be triggered as soon as the file is created
--- no python application found, check your startup logs for errors ---
[pid: 16445|app: -1|req: -1/1] 94.154.82.235 () {42 vars in 752 bytes} [Sun Apr  5 15:00:04 2020] GET / => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
--- no python application found, check your startup logs for errors ---
[pid: 16442|app: -1|req: -1/2] 94.154.82.235 () {44 vars in 719 bytes} [Sun Apr  5 15:00:05 2020] GET /favicon.ico => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
SIGINT/SIGQUIT received...killing workers...
worker 5 buried after 0 seconds
worker 1 buried after 1 seconds
worker 2 buried after 1 seconds
worker 3 buried after 1 seconds
worker 4 buried after 1 seconds
worker 6 buried after 1 seconds
worker 7 buried after 1 seconds
worker 8 buried after 1 seconds
worker 9 buried after 1 seconds
goodbye to uWSGI.
VACUUM: unix socket /home/nameuser/srisovki/configs/srisovki.sock removed.

В виртуальном окружении у меня python3.8 а тут пишет -> Python version: 3.6.9 (default, Nov 7 2019, 10:44:02) [GCC 8.3.0]
Как заставить uwsgi работать с виртуального окружения?
Или дело в правах? Что посмотреть? куда глянуть? Когда все это кончится?

p.s. django в виртуальном окружении установлен -> ModuleNotFoundError: No module named ‘django’

Содержание статьи

Python не находит Django
Disallowed host
Не работает runserver
Web application could not be started

You have X unapplied migrations

ERROR: Can not perform a ‘—user’ install

Python не находит Django

(docker) andreyolegovich.ru@server:~/HelloDjango [0] $ python3 manage.py runserver
Traceback (most recent call last):
File «manage.py», line 8, in <module>
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 <module>
) 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

свои хосты, например так

ALLOWED_HOSTS = ['http://www.andreyolegovich.ru','127.0.0.1','localhost','andreyolegovich.ru','www.andreyolegovich.ru']

Но при обращении к домену в браузере появляется ошибка 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.

Пропишите в нём

os.environ[‘DJANGO_SETTINGS_MODULE’] = ‘Название_нового_прокта.settings’

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.

python3 manage.py migrate

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

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

In this Python Django Tutorial, we will discuss how to solve the ModuleNotFoundError: no module named Django, and we shall also cover the following topics:

  • No module named Django windows 10
  • No module named Django ubuntu
  • No module named Django macOS

No module named Django windows 10

In this section, we will learn how to solve the modulenotfounderror: no module named ‘django’ in windows 10.

No module named Django windows 10
ModuleNotFoundError: No module named Django

For this, firstly check whether you have pip installed or not, by simply writing the command pip in the python terminal. If you have then it’s fine, otherwise, from the internet download a python script called get-pip.py and save it to your local system.

Command:

# Check pip is installed or not

pip

Pip is the package insatller used to install packages from the Python Packages.

Try to be aware of location the file was saved and change the current directory from the command prompt to that location.

#If pip is not installed then

cd path_of_dir_of_get-pip_script

After this, install pip and run the get-pip.py script by writing the following command:

"python .get-pip.py"

Now, to install Django with its dependencies type the following command:

pip install django

Your, error will be resolved. Or, if not resolved then check the following steps.

  • If you installed Django in a virtual environment, make sure it must be activated.
source venv/bin/activate
  • Make sure the Django version you’re installing is compatible with the Python version you have installed.
  • If you have a 64-bit version of Python installed, ensure sure Django is 64-bit as well. In the case of 32 bits, both must be 32 bits.
  • Make sure to include the path to Python in the PATH variable for system and environment variables.
  • Upgrade pip to the most recent version if it is out of date.
python -m pip install --upgrage pip
  • Make sure there are no errors in the import statement as well.

Read: Python Change Django Version

In this section, we’ll learn to resolve the modulenotfounderror: no module named ‘django’ in ubuntu.

To resolve this error, you have to install Django. So, to install Django, firstly, update your locale package with apt:

sudo apt update

Next, check which version of Python you have installed. And make sure it should be compatible with both Ubuntu and Django.

python3 -V

And, in last install the Django through the APT package manager.

sudo apt install python3-django

If you want to install Django with pip, follow the command:

sudo pip install django

With the above steps, your error will be resolved.

Also, check: Python Django vs Pyramid

No module named Django macOS

In this section, we’ll learn to resolve the modulenotfounderror: no module named ‘django’ in macOS.

To resolve this error, you have to install Django. And, before installing Django must check Python is installed or not. If already installed install pip package, and if not installed install python first and then pip package also.

And, after this finally, install Django.

sudo pip install django

With the above steps, your error will be resolved.

You may also like to read the following Django tutorials.

  • Get URL parameters in Django
  • If statement in Django template
  • Django get all data from POST request
  • Convert HTML page to PDF using Django
  • AttributeError module object has no attribute in Django
  • Python Django where to save base template for all apps

In this Python Django Tutorial, we have discussed the Python Django no module Django and we have also covered the following topics:

  • No module named Django windows 10
  • No module named Django ubuntu
  • No module named Django macOS

Bijay Kumar MVP

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

I am using Python 2.7 with mod_python 3.3.1 and mod_wsgi 3.3.

I get an Internal Server Error and this stack trace in the apache logs:

[Thu Apr 21 10:25:37 2011] [error] [client 83.244.243.242]     import django.core.handlers.wsgi [Thu Apr 21 10:25:37 2011] [error] [client
83.244.243.242] ImportError: No module named django.core.handlers.wsgi [Thu Apr 21 10:25:37 2011] [error] [client
83.244.243.242] mod_wsgi (pid=4463): Target WSGI script '/home/one/codebase/campman/wsgi_handler.py' cannot be loaded as Python module. [Thu Apr 21 10:25:37 2011] [error] [client 83.244.243.242] mod_wsgi (pid=4463): Exception occurred processing WSGI script '/home/one/codebase/campman/wsgi_handler.py'. [Thu Apr 21 10:25:37 2011] [error] [client 83.244.243.242] Traceback (most recent call last): [Thu Apr 21 10:25:37 2011] [error] [client
83.244.243.242]   File "/home/one/codebase/campman/wsgi_handler.py", line 13, in <module> [Thu Apr 21 10:25:37 2011] [error] [client
83.244.243.242]     import django.core.handlers.wsgi [Thu Apr 21 10:25:37 2011] [error] [client
83.244.243.242] ImportError: No module named django.core.handlers.wsgi

asked Apr 21, 2011 at 9:43

bigmac's user avatar

1

You may need to tell your WSGI handler where to look for site-packages:

import site
site.addsitedir('/path/to/lib/python2.7/site-packages')

answered Aug 26, 2012 at 17:13

tfitzgerald's user avatar

tfitzgeraldtfitzgerald

4433 silver badges6 bronze badges

Sounds like whatever software you are trying to host depends on and needs you to install django or some of it’s supporting modules for apache. Look into installing these through your distro’s package manager.

answered Apr 21, 2011 at 9:45

Caleb's user avatar

CalebCaleb

11.7k4 gold badges35 silver badges49 bronze badges

2

Look at the WSGIPythonExecutable and WSGIPythonPath apache directives.

Be aware that mod_python and mod_wsgi are mutually exclusive.

answered Jan 14, 2012 at 5:50

Unpaid Oracles's user avatar

1

Понравилась статья? Поделить с друзьями:
  • Wrye bash как изменить порядок загрузки
  • Wot ошибка установки
  • Wot ошибка 9089
  • Worms 4 mayhem как изменить разрешение экрана на 1920х1080
  • Worldguard an unexpected error occurred please see the server console