将django项目移植到apache

django 1.4 apache 2.2 mod_wsgi

使用django1.4创建了一个简单的项目,用python自带的http server运行良好。但是移植到apache上就会出很多问题。比如目录权限、静态文件访问等。

一、apache403 forbidden You don't have permission to access

解决方法:

需要为项目中的wsgi.py设置访问URL,并使项目目录具有访问权限

    WSGIScriptAlias /tdjproj /var/www/vhost1/tdjproj/tdjproj/wsgi.py

    <Directory /var/www/vhost1/tdjproj>
      Allow from all
    </Directory>
    <Directory /var/www/vhost1/tdjproj/tdjproj>
      Order allow,deny
      Allow from all
    </Directory>
二、500 internal server

查看apache 错误日志

[Mon Jul 02 10:26:31 2012] [error] [client 10.7.6.116]     raise ImportError("Could not import settings '%s' (Is it on sys.path?):%s" % (self.SETTINGS_MODULE, e))
[Mon Jul 02 10:26:31 2012] [error] [client 10.7.6.116] ImportError: Could not import settings 'tdjproj.settings' (Is it on sys.path?): No module named tdjproj.settings
解决方法:在wsgi.py中添加

import sys

root = os.path.join(os.path.dirname(__file__), '..')
sys.path.insert(0, root)

参照:http://modwsgi.googlecode.com/files/mod_wsgi-pycon-sydney-2010.pdf

http://download.csdn.net/detail/ppdouble/4412704

三、模板载入错误

访问127.0.0.1/

TemplateDoesNotExist at /

tjob/job_list.html

Request Method:     GET
Request URL:    http://v.python.centos/tdjproj/
Django Version:     1.4
Exception Type:     TemplateDoesNotExist
Exception Value:    

tjob/job_list.html

Exception Location:     /usr/lib/python2.6/site-packages/django/template/loader.py in select_template, line 193
Python Executable:  /usr/bin/python
Python Version:     2.6.6
Python Path:    

['/var/www/vhost1/tdjproj/tdjproj/..',
Template-loader postmortem

Django tried loading these templates, in this order:

    Using loader django.template.loaders.filesystem.Loader:
        /sbin/templates/tjob/job_list.html (File does not exist)
    Using loader django.template.loaders.app_directories.Loader:
        /usr/lib/python2.6/site-packages/django/contrib/auth/templates/tjob/job_list.html (File does not exist)
        /usr/lib/python2.6/site-packages/django/contrib/admin/templates/tjob/job_list.html (File does not exist)
解决方法:

修改settings.py,对模板设置使用绝对路径

import os
SETTINGS_PATH = os.path.normpath(os.path.dirname(__file__))

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.

    # Don't forget to use absolute paths, not relative paths.
#    'templates'
    os.path.join(SETTINGS_PATH, '../templates'),
)
模板载入讨论详见 http://blog.csdn.net/ppdouble/article/details/7709263
四、数据库访问出错,当前使用sqlite3

1.    unable to open database file

perationalError at /

unable to open database file

Request Method:     GET
Request URL:    http://v.python.centos/tdjproj/
Django Version:     1.4
Exception Type:     OperationalError
Exception Value:    unable to open database file

Exception Location:     /usr/lib/python2.6/site-packages/django/db/backends/sqlite3/base.py in _sqlite_create_connection, line 271
Python Executable:  /usr/bin/python
Python Version:     2.6.6
Python Path:    

['/var/www/vhost1/tdjproj/tdjproj/..',
 '/usr/lib/python2.6/site-packages/MySQL_python-1.2.3-py2.6-linux-i686.egg',
 '/usr/lib/python2.6/site-packages/pysqlite-2.6.3-py2.6-linux-i686.egg',
 '/usr/lib/python26.zip',
 '/usr/lib/python2.6',
 '/usr/lib/python2.6/plat-linux2',
 '/usr/lib/python2.6/lib-tk',
 '/usr/lib/python2.6/lib-old',
 '/usr/lib/python2.6/lib-dynload',
 '/usr/lib/python2.6/site-packages',
 '/usr/lib/python2.6/site-packages/gst-0.10',
 '/usr/lib/python2.6/site-packages/gtk-2.0',
 '/usr/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg-info',
 '/usr/lib/python2.6/site-packages/webkit-1.0']

Server time:    Tue, 3 Jul 2012 22:35:13 -0500

Error during template rendering

In template /var/www/vhost1/tdjproj/templates/tjob/job_list.html, error at line 7
解决方法:

对数据库设置绝对路径

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': '/var/www/vhost1/tdjproj/db/tdata.sqlite3',                      # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}
2.    attempt to write a readonly database

解决方法:

使数据库父级路径及数据库文件本身对运行apache的用户具有可读写权限rw

drwxrwxrwx. 2 root root 4096 Jul  5 15:27 db
-rw-rw-rw-. 1 root root 41984 Jul  5 15:27 tdata.sqlite3
五、移植到apache访问django1.4自带的admin tools,CSS,js等静态文件没起作用,如图


方法1:

创建static目录

tdjproj
|-- db
|-- manage.py
|-- static
|-- tdjproj
|-- templates
`-- tjob
在settings.py中设置STATICFILES_DIRS为admin tools所使用静态文件在django源码中的位置

STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    "/usr/lib/python2.6/site-packages/django/contrib/admin/static/",
)
设置STATIC_ROOT

import os
SETTINGS_PATH = os.path.normpath(os.path.dirname(__file__))

STATIC_ROOT = os.path.join(SETTINGS_PATH, '../static')
使用python manage.py collectstatic收集STATICFILES_DIRS中的静态文件到STATIC_ROOT,即拷贝到STATIC_ROOT所设置的目录下面

设置STATIC_URL,在这里我设置为

STATIC_URL = '/tdjproj/static/'
最后修改apache的配置文件,将STATIC_ROOT映射到STATIC_URL

    Alias /tdjproj/static/ /var/www/vhost1/tdjproj/static/
重启apache

方法2:

在settings.py中设置STATIC_URL,然后在apache的配置文件中使用Alias,将STATIC_URL alias到django1.4源码的物理路径并修改权限,比如我的设置

settings.py

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/tdjproj/static/'
#STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
) 
apache的配置文件

    Alias /tdjproj/static/ /usr/lib/python2.6/site-packages/django/contrib/admin/static/
    <Directory /usr/lib/python2.6/site-packages/django/contrib/admin/static/>
      Order allow,deny
      Allow from all
    </Directory>
重启apache,可以看到admin tools的css起作用了


访问URL:

根据apache的配置文件与django项目中settings.py、urls.py(使用通用视图)的设置,使用以下url访问

http://127.0.0.1/tdjproj/  注意此处最后的/不能省略,否则不能从job_list页面转向job_detail页面( 转向链接变为http://127.0.0.1/1 )

http://127.0.0.1/tdjproj/1/

http://127.0.0.1/tdjproj/admin/

参照:

serving-the-admin-files

Note that the Django development server automatically serves the static filesof the admin app (and any other installed apps), but this is not the case whenyou use any other server arrangement. You're responsible for setting up Apache,or whichever media server you're using, to serve the admin files.

The admin files live in (django/contrib/admin/static/admin) of theDjango distribution.

We strongly recommend using django.contrib.staticfiles to handle theadmin files (along with a Web server as outlined in the previous section; thismeans using thecollectstatic management command to collect thestatic files inSTATIC_ROOT, and then configuring your Web server toserveSTATIC_ROOT atSTATIC_URL), but here are threeother approaches:

  1. Create a symbolic link to the admin static files from within yourdocument root (this may require+FollowSymLinks in your Apacheconfiguration).
  2. Use an Alias directive, as demonstrated above, to alias the appropriateURL (probablySTATIC_URL +admin/) to the actual location ofthe admin files.
  3. Copy the admin static files so that they live within your Apachedocument root.
django-contrib-admin

The included administration app django.contrib.admin has for a long timeshipped with a default set of static files such as JavaScript, images andstylesheets. Django 1.3 added a new contrib appdjango.contrib.staticfilesto handle such files in a generic way and defined conventions for staticfiles included in apps.

Starting in Django 1.4, the admin's static files also follow thisconvention, to make the files easier to deploy. In previous versions of Django,it was also common to define anADMIN_MEDIA_PREFIX setting to point to theURL where the admin's static files live on a Web server. This setting has nowbeen deprecated and replaced by the more general settingSTATIC_URL.Django will now expect to find the admin static files under the URL<STATIC_URL>/admin/.

If you've previously used a URL path for ADMIN_MEDIA_PREFIX (e.g./media/) simply make sureSTATIC_URL andSTATIC_ROOTare configured and your Web server serves those files correctly. Thedevelopment server continues to serve the admin files just like before. Readthestatic files howto for more details.


更多讨论详见

自定义web admin tool界面 https://docs.djangoproject.com/en/1.4/intro/tutorial02/#customize-the-admin-look-and-feel

STATIC_ROOT STATIC_URL等介绍 https://docs.djangoproject.com/en/dev/ref/settings/#static-root

STATICFILES_DIRS https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-dirs

https://docs.djangoproject.com/en/dev/howto/static-files/#using-django-contrib-staticfiles

http://stackoverflow.com/questions/9967849/django-1-4-admin-static-files-without-staticfiles-app

http://stackoverflow.com/questions/5537268/django-admin-page-missing-css/11338273#11338273

http://blog.csdn.net/ppdouble/article/details/7673359

https://docs.djangoproject.com/en/1.4/howto/deployment/wsgi/modwsgi/#serving-the-admin-files

https://docs.djangoproject.com/en/dev/releases/1.4/#django-contrib-admin

http://stackoverflow.com/questions/9967849/django-1-4-admin-static-files-without-staticfiles-app

http://stackoverflow.com/questions/11258417/apache403-forbidden-you-dont-have-permission-to-access


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值