2013年2月21日

Django 練習 #001

  1. 建立專案
    django-admin.py startproject Play

    開啟 DOS
    cd C:\Users\Mortiz\Documents\Django\Play
     
  2. 資料庫連線設定
    Play\Settings.py →
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'Play', #Schema(Table)
            'USER': 'Moz',
            'PASSWORD': 'moz123',
            'HOST': '',
            'PORT': ''
        }

  3. 同步資料庫 & model
    python manage.py syncdb
     
  4. 建立程式
    python manage.py startapp First
     
  5. model
    First\model.py →
    from django.db import models
    
    class User(models.Model):
        Account = models.CharField(max_length=12)
        PW      = models.CharField(max_length=12)
        Name    = models.CharField(max_length=50)
        def __unicode__(self):
            return self.Name

  6. view(controller)
    First\views.py →
    from django.shortcuts import render_to_response
    from models import User
    
    def getUserList(request):
        user_lsit = User.objects.order_by('-Name')
        return render_to_response('First/List.html'
                                  , {'data_list':user_lsit}
               )

  7. templates(view)
    Firts\List.html →
    <html><body> It is now  {{ data_list }}.</body></html>

  8. 將 model User添加到 INSTALLED_APPS
    Play\Settings.py →
    INSTALLED_APPS = (
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.sites',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        # New
        'First', # folder name, not class name
    }

  9. 同步 model到 MySQL schema(Table)
    python manage.py syncdb
    model內不可建 id column, django會自動建立做為 primary key
     
  10. 設定 url
    Play\urls.py →
    from django.conf.urls import patterns, include, url
    
    urlpatterns = patterns('',
                           url('^First/$'
                             , 'First.views.getUserList'
                             , name='hello'),
    )

  11. 設定 templates(view)位址
    Play\settings.py →
    TEMPLATE_DIRS = (
        "C:\Users\Mortiz\Documents\Django\Play",
    )

  12. python manage.py runserver 啟動 Server

沒有留言:

張貼留言