Django + Apache + mod_wsgi permission denied - django

I finished the tutorial on Django's site about using mod_wsgi (here), and having substituted my paths as appropriate, results in a big fat "Permission denied." when I try to access /. Here is the stuff I added to httpd.conf (mod_wsgi is enabled earlier in the conf file):
# Django configuration
WSGIScriptAlias / /usr/local/django/billing/apache/django.wsgi
<Directory /usr/local/django/billing/apache/django.wsgi>
Order allow,deny
Allow from all
</Directory>
AliasMatch ^/([^/]*\.css) /usr/local/wsgi/static/styles/$1
Alias /media/ /usr/local/django/billing/media/
Alias /static/ /usr/local/django/billing/static/
<Directory /usr/local/django/billing/static>
Order deny,allow
Allow from all
</Directory>
<Directory /usr/local/django/billing/media>
Order deny,allow
Allow from all
</Directory>
Edit #1:
I've gone through the slides multiple times, from the start: still no joy. Even after opening up the path to the script, chmod'ing every relevant directory to be readable, and chmod'ing the .wsgi script, I still get permission denied. If I change the directory path from /usr/local/django/billing/apache/django.wsgi to have the django.wsgi truncated, the server returns a configuration error, despite that being how it's configured in the slides.

Same configuration, same environment... but everything was working except a simple call to Popen() in one of my django/python routines...
"Permission denied"
Turned out to be SELINUX (enforcing mode) blocking apache.
You can make SELINUX happy with your application by running the following commands:
# semanage fcontext -a -t httpd_sys_rw_content_t '/path/to/your/app(/.*)?'
# restorecon -R -v /path/to/your/app

I had the same problem with permission denied.
https://serverfault.com/questions/357804/apache2-mod-wsgi-django-named-virtual-servers
The specific error is described in:
http://code.google.com/p/modwsgi/wiki/WhereToGetHelp?tm=6#Conference_Presentations

I had the same issue,Sometimes this happends if the WSGI application is located outside of any directories already configured to be accessible to Apache, particularly when it is on your home directory, its good to specify user=username directive.
/etc/apahe2/sites-avaliable/myvhost [section]
WSGIDaemonProcess localhost python-path=/home/hemanth/ecm:/home/env/lib/python2.7/site-packages user=hemanth
WSGIProcessGroup localhost
/etc/apahe2/sites-avaliable/myvhost [full]
<VirtualHost *:80>
ServerAdmin xy#gmail.om
ServerName localhost
ServerAlias localhost
DocumentRoot /home/hemanth/ecm
<Directory /home/hemanth/ecm>
Order allow,deny
Allow from all
</Directory>
WSGIScriptAlias / /home/hemanth/ecm/index.wsgi
WSGIDaemonProcess localhost python-path=/home/hemanth/ecm:/home/env/lib/python2.7/site-packages user=hemanth
WSGIProcessGroup localhost
Alias /static/ /home/hemanth/ecm/static/
Alias /media/ /home/hemanth/ecm/media/
<Directory /home/hemanth/ecm/media/>
Order allow,deny
Allow from all
</Directory>
<Location "/static/">
Options -Indexes
</Location>
ErrorLog /home/hemanth/ecm/error.log
</VirtualHost>
index.wsgi
import os
import sys
import site
# Add the site-packages of the chosen virtualenv to work with
site.addsitedir('/home/hemanth/env/local/lib/python2.7/site-packages')
# Add the app's directory to the PYTHONPATH
sys.path.append('/home/hemanth/ecm')
sys.path.append('/home/hemanth/ecm/ecm')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ecm.settings")
# Activate your virtual env
activate_env="/home/hemanth/env/bin/activate_this.py"
execfile(activate_env, dict(__file__=activate_env))
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

I got it working after installing flask(in venv) and setting the WSGISocketPrefix.
I am deploying on centos6.8 running python3.6 in venv.
The project folder referenced here is the place where the actual django code is stored. The project public folder references here is accessed by the apache and contains simlinks to relevant resources along with the .htaccess and the .wsgi files relevant for the execution
The socket prefix may vary depending on the os and the apache configuration.
The permissions may vary depending on the apache version if you have issues you can change:
Order allow,deny
Allow from all
to
Require all granted
here is my mod_wsgi configuration (httpd.conf)
LoadModule wsgi_module **path to venv**/lib/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so
WSGIPythonHome **path to venv**
WSGIDaemonProcess flask user=**user name** group=**user group**
WSGIProcessGroup flask
WSGISocketPrefix /var/run/wsgi
<Directory **path-to-project-dir**>
Options ExecCGI MultiViews Indexes
MultiViewsMatch Handlers
AddHandler wsgi-script .py
AddHandler wsgi-script .wsgi
DirectoryIndex index.html index.php index.py app.wsgi
Order allow,deny
Allow from all
</Directory>
here is the virtual host (httpd.conf)
<VirtualHost *:80>
DocumentRoot **project public folder**
ServerName **www.project.com**
ServerAlias **project.com**
WSGIScriptAlias / **project public folder**/site.wsgi
Alias /media/ **project public folder**/media/
<Directory **project public folder**/media>
Order allow,deny
Allow from all
</Directory>
Alias /static/ **project public folder**/static/
<Directory **project public folder**/static>
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
here is the site.wsgi file
import os
import sys
import site
# Add the site-packages of the chosen virtualenv to work with
site.addsitedir('**path to venv**/lib/python3.6/site-packages')
# Add the app's directory to the PYTHONPATH
sys.path.append('**path to project folder containing manage.py**')
sys.path.append('**path to project folder containing settings.py**')
os.environ['DJANGO_SETTINGS_MODULE'] = '**project name**.settings'
# Activate your virtual env
#activate_venv.py is an empty python file which will activate
#the virtual environment when executed. Create it manually
activate_env=os.path.expanduser("**path to venv**/bin/activate_venv.py")
exec(open(activate_env).read(), dict(__file__=activate_env))
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
I had to move following two lines from the wsgi.py to "init.py" in the same folder to solve "Applications not ready error"
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
Here is a dump of the packages in the virtual environment
Click==7.0
Django==2.2.1
django-debug-toolbar==1.11
django-redis==4.10.0
django-tastypie==0.14.2
Flask==1.0.2
itsdangerous==1.1.0
Jinja2==2.10.1
MarkupSafe==1.1.1
mod-wsgi==4.6.5
mysqlclient==1.4.2.post1
Pillow==6.0.0
pip==19.1.1
python-dateutil==2.8.0
python-mimeparse==1.6.0
pytz==2019.1
redis==3.2.1
setuptools==41.0.1
simplejson==3.16.0
six==1.12.0
sqlparse==0.3.0
Werkzeug==0.15.4

Related

Static files not being served on AWS Lightsail

After 2 days of trying multiple tutorials & reading StackOverflow, I'm calling for help!
The setting:
The development version is running smoothly on the AWS Lightsail server. It's during the production deployment that I'm running in continuous problems with the static files. The application runs on the appointed subdomain but it's missing all the JS/CSS/images/...
I have followed the official docs but to no avail.
1/ https://docs.bitnami.com/aws/infrastructure/django/get-started/deploy-django-project/
2/ https://docs.bitnami.com/aws/infrastructure/django/get-started/deploy-django-project/
My Folder Tree with relevant files:
Project
- conf
- httpd-app.conf
- httpd-prefix.conf
- Django2Tutorial
- settings.py
- wsgi.py
- Solar
- static
- static (after running collectstatic function in terminal,-it includes the admin, Solar statics)
My settings:
STATIC_ROOT = os.path.join(BASE_DIR,'static')
STATIC_URL = '/static/'
DEBUG = False
ALLOWED_HOSTS = ['54.169.172.***']
wsgi.py file
import os
import sys
sys.path.append('/opt/bitnami/apps/django/django_projects/Project')
os.environ.setdefault("PYTHON_EGG_CACHE", "/opt/bitnami/apps/django/django_projects/Project/egg_cache")
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoTutorial2.settings')
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
My conf files :
1. httpd-app.conf file
<IfDefine !IS_DJANGOSTACK_LOADED>
Define IS_DJANGOSTACK_LOADED
WSGIDaemonProcess wsgi-djangostack processes=2 threads=15 display-name=%{GROUP}
</IfDefine>
<Directory "/opt/bitnami/apps/django/django_projects/Project/DjangoTutorial2">
Options +MultiViews
AllowOverride All
<IfVersion >= 2.3>
Require all granted
</IfVersion>
WSGIProcessGroup wsgi-djangostack
WSGIApplicationGroup %{GLOBAL}
</Directory>
Alias /static "/opt/bitnami/apps/django/django_projects/Project/static"
<Directory "/opt/bitnami/apps/django/django_projects/Project/static">
Require all granted
</Directory>
WSGIScriptAlias / '/opt/bitnami/apps/django/django_projects/Project/DjangoTutorial2/wsgi.py'
2. httpd-prefix.conf file
# Include file
RewriteEngine On
RewriteCond "%{HTTP_HOST}" ^ec2-([0-9]{1,3})-([0-9]{1,3})-([0-9]{1,3})-([0-9]{1,3})\..*\.amazonaws.com(:[0-9]*)?$
RewriteRule "^/?(.*)" "%{REQUEST_SCHEME}://%1.%2.%3.%4%5/$1" [L,R=302,NE]
Include "/opt/bitnami/apps/django/django_projects/Project/conf/httpd-app.conf"
Other adjustments made: (/opt/bitnami/apache2/conf/bitnami)
1/ bitnami-apps-prefix.conf file
Include "/opt/bitnami/apps/django/django_projects/Project/conf/httpd-prefix.conf"
2/ bitnami.conf file
VirtualHost _default_:80>
WSGIScriptAlias / /opt/bitnami/apps/django/django_projects/Project/DjangoTutorial2/wsgi.py
<Directory /opt/bitnami/apps/django/django_projects/Project>
AllowOverride all
Require all granted
Options FollowSymlinks
</Directory>
DocumentRoot /opt/bitnami/apps/django/django_projects/Project
</VirtualHost>
the bitnami-apps-vhosts.conf file is empty? Can this be?
Checked as well:
restarted Apache on multiple occasions
played around with the static_url & static_roots
Can anyone advise how to proceed? It's been extremely frustrating 2 days haha.
Note, maybe this can help :
double-checked with the findstatic function, it redirects me to the Solar/static folder. I thought since I ran collect static, I should point to the Project level static folder in the apache conf & not the Solar level static folder.
You need to add Alias /static/ /opt/bitnami/apps/django/django_projects/Project/static/ to your virtualhost config so the server knows to map /static/ requests to that folder.
I wasted A LOT of time on this, here's my final working bitnami.conf file.
<VirtualHost _default_:80>
WSGIDaemonProcess django_site python-home=/opt/bitnami/projects/env python-path=/opt/bitnami/projects/django_site.com
WSGIProcessGroup django_site
WSGIScriptAlias / /opt/bitnami/projects/django_site.com/django_site/wsgi.py
<Directory /opt/bitnami/projects/django_site.com>
AllowOverride all
Require all granted
Options FollowSymlinks
WSGIProcessGroup django_site
</Directory>
Alias /static/ /opt/bitnami/projects/django_site.com/static/
</VirtualHost>
Include "/opt/bitnami/apache/conf/bitnami/bitnami-ssl.conf"
Note:
I know it's not recommended, but I put all the codes inside bitnami.conf and neglected httpd-app.conf and httpd-prefix.conf
I created python virtualenv at /opt/bitnami/projects/env and installed all needed libraries there
I added the below code to my settings.py file before running python manage.py collectstatic
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'

End of script output before headers: wsgi.py

I am trying to install my django project with Apache, mod_wsgi and python3. but Apache still gives this error:
Exception ignored in: <module 'threading' from '/usr/lib/python3.4/threading.py'>
Traceback (most recent call last):
File "/usr/lib/python3.4/threading.py", line 1288, in _shutdown
assert tlock is not None
AssertionError:
End of script output before headers: wsgi.py
I lost two days trying to fix this problem, I know that this error can be produced by several reasons but I not find where the problem.
Here the wsgi.py content:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import site, sys
path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if path not in sys.path:
sys.path.append(path)
sys.path.append('/var/www/myproject/myproject_env/bin/python3.4/dist-packages')
site.addsitedir('/var/www/myproject/myproject_env/bin/python3.4/dist-packages')
os.environ["DJANGO_SETTINGS_MODULE"] = "myproject.settings"
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
The Apache configuration is as follows:
<VirtualHost *:80>
ServerName mydomain.com
ServerAlias www.mydomain.com
DocumentRoot /var/www
Alias /static/ /var/www/myproject/static/
Alias /static/admin/ /var/www/myproject/static/admin/
Alias /uploads/ /var/www/myproject/uploads/
WSGIDaemonProcess myproject lang='fr_FR.UTF-8' locale='fr_FR.UTF-8' python-path=/var/www/myproject:/var/www/myproject/myproject_env/bin/python3.4/dist-packages
WSGIProcessGroup myproject
WSGIScriptAlias / /var/www/myproject/myproject/wsgi.py
WSGIApplicationGroup %{GLOBAL}
<Directory "/var/www/myproject/myproject/">
Require all granted
</Directory>
<Directory "/var/www/myproject/myproject/wsgi.py">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Require all granted
</Directory>
<Directory /static/admin/>
Require all granted
</Directory>
<Location "/uploads/">
SetHandler None
</Location>
ErrorLog /var/log/apache2/myproject.log
CustomLog /var/log/apache2/myproject.access.log combined
</VirtualHost>
Please anyone helps me fix this?
Solved: I changed the location of my Django project to another folder in a new linux account. I think (and I'm not really sure) the error occurred because /var/www contains another python project using cgi-bin, this maybe creates conflict with my Django project.

Django: Apache Virtual Host giving 500 server error

I don't know why I'm getting this error:
500 - Internal Server Error
In my httpd.conf I put the following code:
<VirtualHost *:80>
WSGIScriptAlias / "/var/django/projects/blunne/blunne/wsgi.py"
ServerName teste.blunne.com
Alias /static "/var/django/projects/blunne/static/"
<Directory "/var/django/projects/blunne/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
What's wrong with this code?
blunne is the name of my application, it works fine on development server.
I tried to change the paths, put the code without quotation, make a custom wsgi in the path: "/var/django/projects/blunne.wsgi" with the following code
import os, sys
sys.path.append(os.sep.join(os.path.abspath('/var/django/projects/blunne/').split(os.sep)))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "blunne.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
But always the same error... If i delete the virtualhost Apache gets normal
.
EDIT: In my localhost with wamp (Windows 7), I can run django with the following:
.
FILE: httpd-vhosts.conf
# httpd.conf includes conf/extra/httpd-vhosts.conf
<VirtualHost *:80>
WSGIScriptAlias / "C:/Django/projects/blunne.wsgi"
ServerName beta.blunne.com
Alias /static "C:/Django/projects/blunne/static/"
<Directory "C:/Django/projects/blunne/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
FILE: C:/Django/projects/blunne.wsgi
import os, sys
#sys.path.append(os.sep.join(os.path.abspath(__file__).split(os.sep)[:-2]))
sys.path.append(os.sep.join(os.path.abspath('C:/Django/projects/blunne/').split(os.sep)))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "blunne.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
Then I configured hosts to
127.0.0.1 beta.blunne.com
I don't know what to do.

Can't get Apache to serve django admin static files

I'm trying to deploy Django to apache but can't get it to serve my static admin files. It seems to be looking for them under /var/www/static and I can't seem to be able to change that.
The admin site seem to be working except for styling. I get a title and a log in form. My django app is working too. It's the static files for the admin that aren't served.
Using Django 1.4.1.
The files are under /usr/local/lib/python2.7/dist-packages/django/contrib/admin/static and linked to from /home/dutt/vaccapp/backend/static/admin.
The apache error log says this
[Sun Sep 30 10:57:20 2012] [error] [client 192.168.1.10] File does not exist: /var/www/home, referer: http://dathui.example.com/vaccapp/admin/
[Sun Sep 30 10:57:20 2012] [error] [client 192.168.1.10] File does not exist: /var/www/home, referer: http://dathui.example.com/vaccapp/admin/
But I'm not sure how to change it.
In my django site config I have
<VirtualHost *:80>
ServerAdmin me#host.com
ServerRoot "/home/dutt/vaccapp"
DocumentRoot "/home/dutt/vaccapp"
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /home/dutt/vaccapp/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
Alias /static/ "/home/dutt/vaccapp/backend/static/"
<Directory "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/static">
Order allow,deny
Options Indexes
Allow from all
IndexOptions FancyIndexing
</Directory>
ServerRoot is not set in apache2.conf.
From my settings.py
STATIC_ROOT = '/home/dutt/vaccapp/backend/'
STATIC_URL = '/static/'
Nothing added to STATICFILES_DIRS.
This is added to my apache2.conf
WSGIScriptAlias /vaccapp /home/dutt/vaccapp/backend/wsgi.py
WSGIPythonPath /home/dutt/vaccapp
<Directory /home/dutt/vaccapp>
<Files wsgi.py>
Order deny,allow
Allow from all
</Files>
</Directory>
ADMIN_MEDIA_PREFIX is set by default to /static/admin/ # Deprecated in Django 1.4 (now using STATIC_URL + 'admin/'. The result is the same.
Here's the fixes to the apache config:
Alias /static/admin "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/static"
Alias /static "/home/dutt/vaccapp/backend/static"
<Directory "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/static">
Order allow,deny
Options Indexes
Allow from all
IndexOptions FancyIndexing
</Directory>
And the WsgiScriptAlias had to be moved from the main apache config into the VirtualHost.
After a long discussion we found the problem was that Django did not install the admin static properly ... they were symlinked to eachother (very weird). A Django reinstall fixed it and it worked fine now.
My low reputation forces me to write a whole answer to add a small detail to Igor's answer.
I simply added the apache config part to my configuration, but it was not sufficient. I had to change:
"/usr/local/lib/python2.7/dist-packages/django/contrib/admin/static"
to
"/usr/local/lib/python2.7/dist-packages/django/contrib/admin/static/admin"
both in the first Alias and in the <Directory> directive.
Just like Blazor I had to use a small variation of the original. My setup includes graphite-web, which is using django admin. I'm just posting it for reference.
My apache's virtual host:
<VirtualHost *:80>
ServerName graphite.myhost.com
Redirect permanent / https://graphite.myhost.com/
</VirtualHost>
<VirtualHost *:443>
ServerName graphite.myhost.com
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/graphite.cert
SSLCertificateKeyFile /etc/apache2/ssl/ssl_graphite.key
SSLStrictSNIVHostCheck on
WSGIDaemonProcess _graphite processes=5 threads=5 display-name='%{GROUP}' inactivity-timeout=120 user=_graphite group=_graphite
WSGIProcessGroup _graphite
WSGIImportScript /usr/share/graphite-web/graphite.wsgi process-group=_graphite application-group=%{GLOBAL}
WSGIScriptAlias / /usr/share/graphite-web/graphite.wsgi
AliasMatch ^/admin/(.*)static/admin(.*)$ /usr/lib/python2.7/dist-packages/django/contrib/admin/static/admin/$2
<Directory "/usr/lib/python2.7/dist-packages/django/contrib/admin/static/admin/">
Order allow,deny
Allow from all
</Directory>
Alias /content/ /usr/share/graphite-web/static/
<Location "/content/">
SetHandler None
</Location>
<Location "/">
Order allow,deny
allow from all
AuthType Basic
AuthName "Restricted Zone"
AuthBasicProvider wsgi
WSGIAuthUserScript /var/www/django_auth.wsgi
Require valid-user
</Location>
ErrorLog ${APACHE_LOG_DIR}/graphite-web_error.log
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/graphite-web_access.log combined
</VirtualHost>
I also added STATIC_URL = 'static/' just to make sure I didn't have any issues with the regex.
Try using next
python manage.py collectstatic
The staticfiles app - Django documentation
I got similar problem when running Django + Apache, the Django admin site misses all styling. This is how I solved it:
apache conf: httpd-app.conf
Alias /static "/...path/to/your/django.../site-packages/django/contrib/admin/static"
<Directory "/...path/to/your/django.../site-packages/django/contrib/admin/static">
Require all granted
</Directory>
The /...path/to/your/django.../ above, you can find it by pip show django

No module named registro.forms in my own local django server [edited]

im setting Django Server in my Ubuntu machine, apache/wsgi, but im getting a error in my view:
was No module named registro.forms now after some code in my wsgi is No module name forms
#registro.views
from registro.forms import ComercioForm
In my laptop is running but not in my server machine
django is running
all database table are syncd
WSGI
#path /srv/www/project/apache/django.wsgi
import is, sys
sys.path.insert(0,'/srv/www')
sys.path.insert(0,'/srv/www/project')
sys.path.insert(0,'/srv/www/') #testing
sys.path.insert(0,'/srv/www/project/') #testing
os.environ['DJANGO_SETTINGS_MODULE']='project.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
httpd.conf
#path /srv/www/project/apache/
Alias /media/ "/srv/www/project/public/admin_tools"
<Directory "/srv/www/project/public/admin_tools">
Allow from all
</Directory>
WSGIScriptAlias "/srv/www/project/apache/django.wsgi"
<Directory "/srv/www/project/apache">
Allow from all
</Directory>
project
#path /etc/apache2/sites-available
<VirtualHost *:80>
ServerName project
DocumentRoot /srv/www/project
<Directory /srv/www/project>
Order allow,deny
Allow from all
</Directory>
WSGIDeamonProcess project processes=2 threads=15 display-name=%{GROUP}
WSGIProcessGroup project
WSGIScriptAlias / /srv/www/project/apache/django.wsgi
</VirtualHost>
Any idea?
thanks
You probably don't have the "registro"-application in your Django-Path. For an example how to fix it, see here
.