django: ทดลองติดตั้ง

 

เที่ยวนี้เอาแบบดิบ ๆ เลย

ติดตั้ง Django

http://www.djangoproject.com/documentation/install/

Install Python
# apt-get install python
+++ mime-support python python-minimal python2.4 python2.4-minimal

Install Apache and mod_python
# apt-get install apache2 libapache2-mod-python
+++ apache2 apache2-mpm-worker apache2-utils apache2.2-common libapache2-mod-python libapr1 libaprutil1 libexpat1 libmagic1 libpcre3 libpq4 libsqlite3-0 python-central

How to use Django with mod_python

http://www.djangoproject.com/documentation/modpython/

Django requires Apache 2.x and mod_python 3.x, and you should use Apache's prefork MPM, as opposed to the worker MPM.
# apt-get install apache2-mpm-prefork
--- apache2-mpm-worker
+++ apache2-mpm-prefork

Get your database running
Django works with PostgreSQL (recommended), MySQL and SQLite.
# apt-get install postgresql-8.1
+++ openssl postgresql-8.1 postgresql-client-8.1 postgresql-client-common postgresql-common ssl-cert

แก้ปัญหาการจัดเรียงภาษาไทยของ postgresql
ตรวจ locales ให้มีภาษาไทย
# dpkg-reconfigure locales
<<<--- (*) th_TH TIS-620
<<<--- (*) th_TH.UTF-8 UTF-8

inintdb ใหม่ให้เรียงตามภาษาไทย โดยจะสร้างไดเรคทอรี่ของข้อมูลใหม่ ให้อยู่ที่ /server1/var/lib/postgresql/8.1/main
# /etc/init.d/postgresql-8.1 stop
# mkdir -p /server1/var/lib/postgresql/8.1/main
# chown -R postgres:postgres /server1/var/lib/postgresql
# su postgres
$ /usr/lib/postgresql/8.1/bin/initdb -D /server1/var/lib/postgresql/8.1/main --locale=th_TH.UTF-8 --pgdata=/server1/var/lib/postgresql/8.1/main
$ cd /server1/var/lib/postgresql/8.1/main
$ ln -sf /etc/postgresql-common/root.crt .
$ ln -sf /etc/ssl/certs/ssl-cert-snakeoil.pem server.crt
$ ln -sf /etc/ssl/private/ssl-cert-snakeoil.key server.key
$ exit
# cd /etc/postgresql/8.1/main
# rm pgdata
# ln -sf /server1/var/lib/postgresql-8.1/main pgdata
# /etc/init.d/postgresql-8.1 start

ปรับให้ผู้ใช้ในระบบสามารถเข้ามาใช้งานโดยใช้รหัสผ่านของระบบ
# vi /etc/postgresql/8.1/main/pg_hba.conf

...
# TYPE  DATABASE    USER        CIDR-ADDRESS          METHOD
host    all        all        192.168.1.0/24        md5
...

สร้างผู้คุมฐานข้อมูล
# su postgres
$ psql template1
template1=# CREATE USER superx SUPERUSER PASSWORD 'superx';
template1=# \q
$ exit

ติดตั้ง phppgadmin
# apt-get install phppgadmin
+++ libapache2-mod-php4 libzzip-0-12 php4-common php4-pgsql phppgadmin wwwconfig-common

# dpkg-reconfigure phppgadmin
Which web server would you like to reconfigure automatically?
<<<--- Apache2

# vi /etc/apache2/conf.d/phppgadmin

# deny from all
allow from all

# /etc/init.d/apache2 restart

If you're using PostgreSQL, you'll need the psycopg package
# apt-get install python-psycopg python-psycopg2
+++ python-egenix-mxdatetime python-egenix-mxtools python-psycopg python-psycopg2

Install the Django code

Download Django-0.95.tar.gz from our download page.
# cd /usr/src
# tar xfz Django-0.95.tar.gz
# cd Django-0.95

Note that the last command will automatically download and install setuptools if you don't already have it installed. This requires a working Internet connection.
# apt-get install python-setuptools
+++ python-setuptools

# python setup.py install

เสร็จ Django

เรียน Django

http://www.sitepoint.com/article/build-to-do-list-30-minute

จะสร้างไดเรคทอรี่ของเว็บ โดยให้ webmaster เป็นเจ้าของ
# useradd -m -g www-data webmaster
# su webmaster
$ cd
$ mkdir django
$ cd django

Diving In
จะสร้างโปรเจคต์ ชื่อ gtd
$ django-admin.py startproject gtd
$ cd gtd

รันเซิร์ฟเวอร์ที่พอร์ต 8000 ไอพี 192.168.1.5
$ python manage.py runserver 192.168.1.5:8000

ทดสอบโดย เอาบราวเซอร์ไปที่ http://192.168.1.5:8000/

หยุดเซิร์ฟเวอร์ด้วย Ctrl-C

จะสร้างแอปพลิเกชั่น todo
$ python manage.py startapp todo
$ cd todo
$ vi models.py

class List(models.Model):
  title = models.CharField(maxlength=250, unique=True)
  def __str__(self):
    return self.title
  class Meta:
    ordering = ['title']
  class Admin:
    pass

import datetime

PRIORITY_CHOICES = (
  (1, 'Low'),
  (2, 'Normal'),
  (3, 'High'),
)

class Item(models.Model):
  title = models.CharField(maxlength=250)
  created_date = models.DateTimeField(default=datetime.datetime.now)
  priority = models.IntegerField(choices=PRIORITY_CHOICES, default=2)
  completed = models.BooleanField(default=False)
  todo_list = models.ForeignKey(List)
  def __str__(self):
    return self.title
  class Meta:
    ordering = ['-priority', 'title']
  class Admin:
    pass

$ cd ..

$ su postgres
postgres@server1$ psql template1
template1=# CREATE DATABASE "django" WITH ENCODING='UTF8';
template1=# \q
postgres@server1$ exit

$ vi settings.py

...
DATABASE_ENGINE = 'postgresql'
DATABASE_NAME = 'django'
DATABASE_USER = 'USER1'
DATABASE_PASSWORD = 'USER1PASSWORD'
...
DATABASE_PORT = '5432'
...
TIME_ZONE = 'Asia/Bangkok'
...
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'gtd.todo',
)

$ python manage.py syncdb
You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no):
<<<--- yes
Username (Leave blank to use 'webmaster'):
<<<--- {DEFAULT}
E-mail address:
<<<--- webmaster@example.com
Password:
<<<--- {WEBMASTER-PASSWORD}
Password (again):
<<<--- {WEBMASTER-PASSWORD}

$ vi settings.py

...
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'gtd.todo',
    'django.contrib.admin',
)

$ vi urls.py

...
     (r'^admin/', include('django.contrib.admin.urls')),
...

$ python manage.py syncdb

เริ่มรัน
$ python manage.py runserver 192.168.1.5:8000

เอาบราวเซอร์ไปที่ http://192.168.1.5:8000/admin
Username:
<<<--- webmaster
Password:
<<<--- {WEBMASTER-PASSWORD}

ลองเพิ่มผู้ใช้และกรุ๊ปดู

Deliving into Views

$ cd todo
$ vi views.py

...
from django.shortcuts import render_to_response
from gtd.todo.models import List

def status_report(request):
 todo_listing = []
 for todo_list in List.objects.all():
   todo_dict = {}
   todo_dict['list_object'] = todo_list
   todo_dict['item_count'] = todo_list.item_set.count()
   todo_dict['items_complete'] = todo_list.item_set.filter(completed=True).count()
   todo_dict['percent_complete'] = int(float(todo_dict['items_complete']) / todo_dict['item_count'] * 100)
   todo_listing.append(todo_dict)
 return render_to_response('status_report.html', { 'todo_listing': todo_listing })

Writing the Template

$ mkdir templates
$ cd templates
$ vi status_report.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <title>To-do List Status Report</title>
 </head>
 <body>
   <h1>To-do list status report</h1>
{% for list_dict in todo_listing %}
   <h2>{{ list_dict.list_object.title }}</h2>
   <ul>
     <li>Number of items: {{ list_dict.item_count }}</li>
     <li>Number completed: {{ list_dict.items_complete }} ({{ list_dict.percent_complete }}%)</li>
   </ul>
{% endfor %}
 </body>
</html>

Making it Work

$ cd ../..
$ vi settings.py

...
TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates".
    # Always use forward slashes, even on Windows.
    '/home/webmaster/django/gtd/todo/templates',
)

$ vi urls.py

...
urlpatterns = patterns('',
    # Example:
    # (r'^gtd/', include('gtd.apps.foo.urls.foo')),

    # Uncomment this for admin:
    (r'^admin/', include('django.contrib.admin.urls')),
    (r'^report/$', 'gtd.todo.views.status_report'),
)

$ python manage.py runserver 192.168.1.5:8000

ลองดูที่บราวเซอร์ http://192.168.1.5:8000/report

เรียบร้อย

 

Syndicate

Subscribe to Syndicate

Who's online

There are currently 0 users online.