skip to Main Content

I’m trying to install and run Django in a sub-directory, to isolate it and a static html site in root; these two questions haven’t helped and are very old: install django on subdirectory and Configure django on sub directory

Is this a file/folder permissions, Apache user, virtualhosts or Python issue?

Why are the .py files not executing?


Outline:

  • I’m running Ubuntu 20.04.3 LTS
  • Apache2 was already installed and is running
  • Python3 and Django installed
  • libapache2-mod-wsgi-py3 installed and enabled
  • apachectl configtest Syntax OK
  • All files chowned to www-data:www-data

/var/log/apache2/access.log is empty

/var/log/apache2/error.log contains:

[mpm_prefork:notice] [pid 69090] AH00163: Apache/2.4.41 (Ubuntu)
OpenSSL/1.1.1k mod_wsgi/4.6.8 Python/3.8 configured — resuming normal
operations

[core:notice] [pid 69090] AH00094: Command line: ‘/usr/sbin/apache2’


I ran the usual shell commands to start a Django project:

root@localhost:~# django-admin.py startproject contact

and then I ran createsuperuser, collectstatic, etc., successfully.

I’m trying to use a Django form that is in /contact/contactform/templates/contact.html that contains this:

<form action="/contact/" method="post">
                {% csrf_token %}
                {{ form.as_p }}
            <div class="frc-captcha mb-2" data-sitekey={{ captcha_site_key }}></div>
        <button type="submit" class="btn btn-primary">Send</button>
</form>

and going to https://example.com/contact/ throws a 403 error.

The .htaccess file at root has

RewriteEngine on
ServerSignature Off
Options All -Indexes

This is my public_html file structure:

enter image description here

/contact/contact/settings.py

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

SECRET_KEY = '...'

DEBUG = True

ALLOWED_HOSTS = []

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'contact.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'contact.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(BASE_DIR, "static/")

/etc/apache2/sites-available/default-ssl.conf:

    <IfModule mod_ssl.c>
    <VirtualHost _default_:443>
        ServerAdmin webmaster@localhost

        DocumentRoot /var/www/html

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        SSLEngine on

        SSLCertificateFile  /etc/ssl/certs/ssl-cert-snakeoil.pem
        SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key

        #SSLCertificateChainFile /etc/apache2/ssl.crt/server-ca.crt

        #SSLCACertificatePath /etc/ssl/certs/
        #SSLCACertificateFile /etc/apache2/ssl.crt/ca-bundle.crt

        <FilesMatch ".(cgi|shtml|phtml|php)$">
                SSLOptions +StdEnvVars
        </FilesMatch>
        <Directory /usr/lib/cgi-bin>
                SSLOptions +StdEnvVars
        </Directory>


Alias /static /var/www/html/example.com/public_html/contact/static
Alias /media /var/www/html/example.com/public_html/contact/media

<Directory /var/www/html/example.com/public_html/contact/static>
    Require all granted
</Directory>

<Directory /var/www/html/example.com/public_html/contact/media>
    Require all granted
</Directory>

WSGIScriptAlias /contact/contact /var/www/html/example.com/public_html/contact/contact/wsgi.py

WSGIDaemonProcess contact python-home=/var/www/html/example.com/public_html/contact/contact

WSGIProcessGroup contact

WSGISocketPrefix run/wsgi

 <Directory /var/www/html/example.com/public_html/contact/contact>
    <Files wsgi.py>
        Require all granted
    </Files>
</Directory>

    </VirtualHost>
</IfModule>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

/contact/contact/wsgi.py:

import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'contact.settings')
application = get_wsgi_application()

/contact/contact/urls.py:

from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('contactform.urls', namespace='contactform')),
]

/contact/contactform/urls.py:

from django.urls import path
from . import views
app_name = 'contact'

urlpatterns = [
    path('thanks/', views.thanks, name='thanks'),
    path('contact/', views.contact, name='contact'),
]

2

Answers


  1. Chosen as BEST ANSWER

    This is what finally worked for me:

    I needed to add the #added lines in wsgi.py (from https://www.metaltoad.com/blog/hosting-django-sites-apache )

    import os
    
    import sys #added
    
    sys.path.append('/var/www/html/contact')  #added
    
    from django.core.wsgi import get_wsgi_application
    
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'contact.settings')
    
    application = get_wsgi_application()
    

    And rather than edit /etc/apache2/sites-available/default-ssl.conf, I edited /etc/apache2/apache2.conf:

    Alias /static /var/www/html/example.com/public_html/contact/static
    Alias /media /var/www/html/example.com/public_html/contact/media
    
    <Directory /var/www/html/example.com/public_html/contact/static>
        Require all granted
    </Directory>
    
    <Directory /var/www/html/example.com/public_html/contact/media>
        Require all granted
    </Directory>
    
    WSGIScriptAlias /contact  /var/www/html/example.com/public_html/contact/contact/wsgi.py process-group=contact
    
    WSGIDaemonProcess contact  python-path=/var/www/html/example.com/public_html/contact
    
    WSGIProcessGroup contact
    
    <Directory  /var/www/html>
    Options Indexes FollowSymLinks
    AllowOverride all
    Require all granted
    
    <Files wsgi.py>
    Require all granted
    </Files>
    </Directory>
    

  2. One line of your 000-default.conf is defining the path to your python executable :

    WSGIDaemonProcess contact python-path=/var/www/html/example.com/public_html/contact python-home=/var/www/html/example.com/public_html/contact/contact
    

    If you want to let apache find the python used in the shell, you should remove the python-path argument

    WSGIDaemonProcess contact python-home=/var/www/html/example.com/public_html/contact/contact
    

    Or make it point to your python3 installation

    WSGIDaemonProcess contact python-path=/my/python3/path python-home=/var/www/html/example.com/public_html/contact/contact
    

    That way you will stop having a warning about python2.7 being used and it may help your project working

    You should also ensure that your mod-wsgi was installed using python3 and not using python2.7

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search