在Ubuntu服务器上部署django网站(Apache2)

基本环境部署:

~# apt-get install python-pip
~# pip install Django

Create project djangosite,  and start app helloworld

root@localhost:/srv/www# django-admin startproject djangosite
root@localhost:/srv/www# cd djangosite
root@localhost:/srv/www/djangosite# python manage.py startapp helloworld

修改helloworld应用目录下的view.py文件

root@localhost:/srv/www/djangosite/helloworld# vi views.py

#coding:utf-8
from django.http import HttpResponse
from django.shortcuts import render

def index(request):
    return HttpResponse(u"Hello World!")

新定义的app加到settings.py中的INSTALL_APPS中

root@localhost:/srv/www/djangosite# vi djangosite/settings.py

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

    'helloworld',
)

修改url.py定义访问路径

root@localhost:/srv/www/djangosite/djangosite# vi urls.py 

from django.conf.urls import patterns, include, url
from django.contrib import admin

admin.autodiscover()

urlpatterns = [

    url(r'^$', 'helloworld.views.index', name = 'home'),
    url(r'^admin/', include(admin.site.urls)),
]

至此,django这边的配置结束,网站已经可以使用managy.py runserver运行,并通过127.0.0.1:8000的localhost访问。

下面配置Apache2使得网站能够通过域名进行外部访问。

root@localhost:/# vi /etc/apache2/sites-available/django.zivers.com.conf 

<VirtualHost *:80>
        ServerName django.zivers.com
        ServerAdmin webmaster@localhost
        DocumentRoot /srv/www/djangosite/

        WSGIScriptAlias / /srv/www/djangosite/djangosite/wsgi.py

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

修改wsgi文件

root@localhost:/# vi /srv/www/djangosite/djangosite/wsgi.py

import os
from os.path import join, dirname, abspath

PROJECT_DIR = dirname(dirname(abspath(__file__)))
import sys
sys.path.insert(0, PROJECT_DIR)

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

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

启用配置并重启Apache2

root@localhost:/srv/www/djangosite/djangosite# a2ensite django.zivers.com.conf
root@localhost:/srv/www/djangosite/djangosite# servcie apache2 reload

这时候网站已经能通过django.zivers.com正常访问

20151126102135

 

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注