Deploy Django on Apache?

2019-03-03 18:36发布

问题:

I create project using Django 1.8. now ,I want deploy it to server.when I run this command in Ubuntu every thing working find.

python manage.py runserver

Next , I create vertuelhost and enbal key.com site in Apache.

vertualhost file code. ( key.com.conf )

<VirtualHost *:80>
    ServerAdmin admin@key.com
    ServerName key.com
    ServerAlias www.key.com
    WSGIScriptAlias / /home/umayanga/Desktop/view_site/serialKey_gen_site/mysite/wsgi.py
    <Directory "/home/umayanga/Desktop/view_site/serialKey_gen_site/mysite">
        Options Indexes FollowSymLinks
        AllowOverride all
        Require all granted

        <Files wsgi.py>
               Require all granted
        </Files>
    </Directory>
</VirtualHost>

the following image show my project folder structure.

now , I run , key.com url , it gives 500 server internal error. I will check Apache error log fie. I t contain following things.

    [Tue Nov 24 15:16:50.317896 2015] [:error] [pid 12505] [client 127.0.0.1:37918] mod_wsgi (pid=12505): Exception occurred processing WSGI script '/home/umayanga/Desktop/view_site/serialKey_gen_site/mysite/wsgi.py'.
[Tue Nov 24 15:16:50.317982 2015] [:error] [pid 12505] [client 127.0.0.1:37918] Traceback (most recent call last):
[Tue Nov 24 15:16:50.318011 2015] [:error] [pid 12505] [client 127.0.0.1:37918]   File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 187, in __call__
[Tue Nov 24 15:16:50.318117 2015] [:error] [pid 12505] [client 127.0.0.1:37918]     self.load_middleware()
[Tue Nov 24 15:16:50.318131 2015] [:error] [pid 12505] [client 127.0.0.1:37918]   File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 44, in load_middleware
[Tue Nov 24 15:16:50.318236 2015] [:error] [pid 12505] [client 127.0.0.1:37918]     for middleware_path in settings.MIDDLEWARE_CLASSES:
[Tue Nov 24 15:16:50.318249 2015] [:error] [pid 12505] [client 127.0.0.1:37918]   File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 54, in __getattr__
[Tue Nov 24 15:16:50.318325 2015] [:error] [pid 12505] [client 127.0.0.1:37918]     self._setup(name)
[Tue Nov 24 15:16:50.318337 2015] [:error] [pid 12505] [client 127.0.0.1:37918]   File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 49, in _setup
[Tue Nov 24 15:16:50.318355 2015] [:error] [pid 12505] [client 127.0.0.1:37918]     self._wrapped = Settings(settings_module)
[Tue Nov 24 15:16:50.318364 2015] [:error] [pid 12505] [client 127.0.0.1:37918]   File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 132, in __init__
[Tue Nov 24 15:16:50.318380 2015] [:error] [pid 12505] [client 127.0.0.1:37918]     % (self.SETTINGS_MODULE, e)
[Tue Nov 24 15:16:50.318399 2015] [:error] [pid 12505] [client 127.0.0.1:37918] ImportError: Could not import settings 'mysite.settings' (Is it on sys.path? Is there an import error in the settings file?): No module named mysite.settings

expect some expert help.

=======================wsgi.py============

    """
WSGI config for test2 project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""

import os,sys
sys.path.append('/home/umayanga/Desktop/view_site/serialKey_gen_site/mysite')

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

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

===================setting.py==================================

    """
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 1.8.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

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


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '-vvzx5(=sztv%*^ljnpkdc&!q+ltws0-%a76^v1e_z9g97-k2%'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'marcador',
    'crispy_forms',
    'bootstrap_pagination',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        '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 = 'mysite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

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


# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Europe/Berlin'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)


LOGIN_URL = 'mysite_login'
LOGOUT_URL = 'mysite_logout'
LOGIN_REDIRECT_URL = 'marcador_bookmark_list'



CRISPY_TEMPLATE_PACK = 'bootstrap3'

回答1:

As I said in the comments, you're not doing anything to add your project to the PYTHONPATH so that the WSGI app can actually find it.

It seems from your directory structure that you're using a virtualenv; you need to activate that either within the .wsgi file or in the Apache configuration itself. The Django docs recommend the latter.



回答2:

finally I could successfully deploy my project.I enabled Apache this module early.

refer this link

--------------this is my virtual host file----------------------------------

WSGIPythonPath /home/umayanga/Desktop/view_site/serialKey_gen_site:/home/umayanga/Desktop/view_site/serialKey_gen_site/myvenv/lib/python3.4/site$

<VirtualHost *:80>
    ServerAdmin admin@key.com
    ServerName key.com
    ServerAlias www.key.com

    Alias /templates/ /home/umayanga/Desktop/view_site/serialKey_gen_site/templates/
    Alias /static/ /home/umayanga/Desktop/view_site/serialKey_gen_site/static/


    <Directory "/home/umayanga/Desktop/view_site/serialKey_gen_site/static">
           Require all granted
    </Directory>

    <Directory "/home/umayanga/Desktop/view_site/serialKey_gen_site/templates">
           Require all granted
    </Directory>

    WSGIScriptAlias / /home/umayanga/Desktop/view_site/serialKey_gen_site/mysite/wsgi.py

    <Directory "/home/umayanga/Desktop/view_site/serialKey_gen_site/mysite">
        Options Indexes FollowSymLinks
        AllowOverride all
        Require all granted
        <Files wsgi.py>
               Require all granted
        </Files>
    </Directory>

</VirtualHost>

-----------------wsgi.py---------------------------------------

"""
WSGI config for mysite project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application



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

application = get_wsgi_application()

I think this will be help to other Django developers.Thank you all developers those who help me.



回答3:

In your wsgi.py try changing

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

to

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

Since both files are in the same directory/module.