日記

日々のことと、Python/Django/PHP/Laravel/nodejs などソフトウェア開発のことを書き綴ります

初めてのアプリケーション構築

プロジェクトとその中にアプリケーションを作ります。

django-admin.py startproject sample
cd sample
manage.py startapp app1


settings.pyを開いて INSTALLED_APPSにapp1を追加、TEMPLATE_DIRSにtemplate_dirを追加します。

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.
    'template_dir',
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'app1',
)

次に urls.pyを開いてブラウザからアクセスするURLを設定します。

urlpatterns = patterns('',
    # Example:
    # (r'^sample/', include('sample.foo.urls')),
    
    (r'^sample/first$', 'app1.views.first'),
    
    # Uncomment the admin/doc line below and add 'django.contrib.admindocs' 
    # to INSTALLED_APPS to enable admin documentation:
    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # (r'^admin/', include(admin.site.urls)),
)


続いて、app1/views.py を編集します。

from django.shortcuts import render_to_response

def first(request):
    return render_to_response('first.html', {})


次に、views.pyのfirstが使用している first.htmlを作成します。
作成場所は プロジェクトの直下に "template_dir" ディレクトリを作成してその中にファイルを作ります。

<html>
<head>
</head>
<body>
<p>サンプルアプリケーション はじめの一歩</p>
</body>
</html>

まだ動的な個所を入れていないので、普通のHTMLと一緒です。
ここまで出来たら、djangoのWebサーバを起動します。

manage.py runserver

ブラウザでアクセスするときは

http://localhost:8000/sample/first

でアクセスできます。